Internal Server Error on kendo grid update with ajax - ajax

i m trying to update grid with ajax but i couldn't success in passing and getting values between controler and view with ajax
When i run program its output is like that
[object Object]++error++Internal Server Error
So i need help
HomeController Function
[HttpGet]
public ActionResult RssCek(string value)
{
XDocument rssXml = new XDocument();
switch (value)
{
case "Ekonomi":
{
rssXml = XDocument.Load("http://sozcu.com.tr/rss.php");
break;
}
case "Siyaset":
{
rssXml = XDocument.Load("http://www.milliyet.com.tr/D/rss/rss/Rss_4.xml");
break;
}
case "Yaşam":
{
rssXml = XDocument.Load("http://www.milliyet.com.tr/D/rss/rss/Rss_5.xml");
break;
}
default:
{
rssXml = XDocument.Load("http://sozcu.com.tr/rss.php");
}
break;
}
var feedler = from feed in rssXml.Descendants("item")
select new Rss
{
Baslik = feed.Element("title").Value,
Link = "Oku",
Aciklama = feed.Element("description").Value
};
var valueToReturn = new JsonResult { Data = feedler };
return valueToReturn;
}
IndexView Grid Code
#Html.Kendo().Grid(Model)
.Name("Grid").Pageable()
.Columns(columns =>
{
columns.Bound(p => p.Baslik).Groupable(false);
columns.Bound(p => p.Aciklama).Encoded(false);
columns.Bound(p => p.Link).Encoded(false);
})
.DataSource(dataSource => dataSource
.Ajax()
.Read(read => read.Action("RssCek", "Home"))
)
IndexView JavaScript Code
<script>
function select(e) {
var value = $(e.item).find("> .k-link").text();
$.ajax({
url: '#Url.Action("RssCek", "Home")',
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: { value: value},
success: function (feedler)
{
document.write(feedler);
},
error: function (request, status, error)
{document.write(request+"++"+ status+"++"+ error);}
});
}
</script>

I found problem is caused by missing JsonRequestBehavior.AllowGet
return Json(feedler, JsonRequestBehavior.AllowGet);
instead of ;
var valueToReturn = new JsonResult { Data = feedler };
return valueToReturn;

Related

Ajax PostBack: Read data from Controller

How do I read the data from my controller in my ajax postback?
I have a Razor form
#using (Html.BeginForm("CreateDocument", "Pages", FormMethod.Post, new { id = "createDocumentForm" }))
{
....
}
And I catch the Submit action in JavaScript:
<script type="text/javascript">
$(document).ready(function () {
$("#createDocumentForm").submit(
function () {
showWaitMode();
$.ajax({
data: ("#createDocumentForm").serialize,
success: (e) => {
console.log(e);
},
error: (errorResponse) => {
alert(errorResponse)
}
})
return false;
}
);
});
</script>
In my controller I hit this method:
public ActionResult CreateDocument(NotatFletModel model)
{
var reuslt = new
{
Staus = true,
GoDocumentId = model.ContactId.ToString(),
ErrorMessage = model.DocumentKindId,
};
return Json(reuslt);
}
But in my Ajax success function I would like to get the data from my contorller. I expected it to be in my parameter e but it's not
So in short: How do I do an Ajax post and read the data posted back from the controller
Checkout my code for Form Post using ajax
Html :
#using (Html.BeginForm("CreateDocument", "Pages", FormMethod.Post, new { id = "createDocumentForm" }))
{
....
}
Jquery :
$("#createDocumentForm").submit(
function (e) {
showWaitMode();
e.preventDefault();
var form = $(this);
var url = form.attr('action');
$.ajax({
url: url,
type: 'POST',
data: form.serialize(), // serializes the form's elements.
success: function (data) {
console.log(data); // show response
},
error: (errorResponse) => {
alert(errorResponse)
}
})
return false;
}
);
Controller :
//You can Use FormCollection also to get data
//public ActionResult CreateDocument(FormCollection fc) {
[HttpPost]
public ActionResult CreateDocument(NotatFletModel model) {
//your logic
return Json(model, JsonRequestBehavior.AllowGet);
}

Kendo Grid Aggregate Sum Displaying always 0

I have Combobox event that call ajax function to fill grid datasource.
i can see my grid correctly filled but aggregate Sum display always 0.
What can i do?
AJAX call
$.ajax({
url: '#Url.Action("CreaGrid3", "Sales")',
dataType: "json",
contentType: "application/json; charset=utf-8",
data: { bra: brand, mod: model, prj: project, ver: version, rel: release },
success: function (result) {
var grid = $("#Grid3").data("kendoGrid");
var dataSource = new kendo.data.DataSource({
data: result.Data
});
grid.setDataSource(dataSource);
grid.dataSource.read();
}
Here my view:
#(Html.Kendo().Grid<IndSudUI.Models.TabTemp3>()
.Name("Grid3")
.Columns(columns =>
{
columns.Bound(e => e.DESCRIZIONE);
columns.Bound(e => e.Totale)
.Format("{0:C3}")
.ClientFooterTemplate("Sum: #=sum#");
})
.Pageable()
.Sortable()
.Scrollable()
.Resizable(resize => resize.Columns(true))
.DataSource(dataSource => dataSource
.Ajax()
.Aggregates(a =>
{
a.Add(p => p.Totale).Sum();
})
.ServerOperation(false)
)
.Events(events => events.DataBound("onDataBound5"))
)
Here my Controller
I removed some parts of code that are not relevant
public JsonResult CreaGrid3([DataSourceRequest] DataSourceRequest request, string bra, string mod, string prj, string ver, string rel)
{
if (!String.IsNullOrEmpty(bra))
bra = bra.Trim();
if (!String.IsNullOrEmpty(mod))
mod = mod.Trim();
if (!String.IsNullOrEmpty(prj))
prj = prj.Trim();
if (!String.IsNullOrEmpty(ver))
ver = ver.Trim();
if (!String.IsNullOrEmpty(rel))
rel = Convert.ToDateTime(rel.Trim()).ToString("yyyyMMdd");
try
{
List<TabTemp3> Listed = new List<TabTemp3>();
var connection = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
DataTable dt = new DataTable();
string sqlcmd = "SELECT l.DESCRIZIONE, CASE WHEN m.PezziTurnoStd=0 THEN 0 ELSE (8 / CONVERT(decimal, m.PezziTurnoStd)) * pr.CostoOraDir * m.PersonaleDirettoStd END Totale FROM ";
sqlcmd = sqlcmd + "AHE.dbo.Inds0DbParArt AS m INNER JOIN ";
//... ETC ...
using (var dataAdapter = new SqlDataAdapter(sqlcmd, connection))
{
dataAdapter.Fill(dt);
}
foreach (DataRow row in dt.Rows)
{
Listed.Add(new TabTemp3
{
DESCRIZIONE = row["DESCRIZIONE"].ToString(),
Totale = (decimal)(row["Totale"])
});
}
var temp = Listed.AsEnumerable<TabTemp3>();
return Json(temp.ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
catch (Exception e)
{
System.Windows.Forms.MessageBox.Show("" + e);
}
return null;
}

Passing the Model back to Server when doing Ajax

here's the code in my .cshtml:
#model WebComposite.Models.MyModel
#using (Html.BeginForm())
{
#Html.TextBoxFor(m => m.id)
#Html.TextBoxFor(m => m.name)
}
#Scripts.Render("~/Scripts/MyScript.js")
here's the code in MyScript.js:
$('form').submit(function (e)
{
e.preventDefault();
//normal Ajax (my own custom version as i'm sure every one has one of these:)
SimpleAjax("MyAction", function () { alert("Done"); });
});
And the Controller code:
[HttpPost]
public ActionResult MyAction(MyModel model)
{
//Problem here is model.id and model.name are empty
}
any ideas?
thanks in advance
After a quick look around I guess the solution is pretty darn simple (thank you jquery!!):
Simply serialize everything you have in the form and post it back to the controller from your ajax call:
$("form").serializeArray();
Here's my own full implementation of Ajax calls
There are 3 functions (you'll to call SimplAjaxPost(url, funcDelegate) and it will do the rest for you
function Ajax(url, dataObj, getOrPost, theContext, theContentType, theDataType, successFuncName, failedFuncName, alwaysFuncName)
{
//GET or POST:
if (getOrPost == null) { getOrPost = 'POST'; }
//Header (what we're sending to the server): http://stackoverflow.com/questions/2722750/ajax-datatype
if (theContentType == null) { theContentType = 'application/x-www-form-urlencoded; charset=UTF-8'; }
//response (what we're expeting in return):http://stackoverflow.com/questions/2722750/ajax-datatype
if (theDataType == null) { theDataType = ""; }
//exposing "this" to whatever: http://stackoverflow.com/questions/5097191/ajax-context-option
if (theContext == null) { theContext = document.body; }
var theURL = NoCache(url);
$.ajax(
{
url: theURL,
data: dataObj,
type: getOrPost,
contentType: theContentType,
dataType: theDataType,
context: theContext,
async: false,
success: successFuncName,
fail: failedFuncName,
always: alwaysFuncName,
complete: AjaxScripts
});
}
function SimpleAjax(url, successFunctionName)
{
var dataObj = null;
Ajax(url, dataObj, null, null, null, null, successFunctionName, null, null)
}
function SimpleAjaxPost(url, successFunctionName)
{
var dataObj = null;
if ($("form").length == 1)
{
dataObj = $("form").serializeArray();
}
Ajax(url, dataObj, null, null, null, null, successFunctionName, null, null)
}
function NoCache(url)
{
var t = new Date();
var qps = "?";
if (url.indexOf("?") > 0)
{
qps = "&";
}
return url + qps + t.getYear() + t.getMonth() + t.getDay() + t.getHours() + t.getMinutes() + t.getSeconds() + t.getMilliseconds();
}

MVC3 and Twitter Bootstrap TypeAhead without plugin

I have gotten TypeAhead to work properly with static data and am able to call my controller function properly and get data but it is either A: Not parsing the data properly or B: The TypeAhead is not set up correctly.
JavaScript :
<input type="text" id="itemSearch" data-provide="typeahead" value="#ViewBag.Item" name="itemSearch"/>
$('#itemSearch').typeahead({
source: function (query, process) {
parts = [];
map = {};
$.ajax({
url: '#Url.Action("MakePartsArray")',
dataType: "json",
type: "POST",
data: {query: query},
success: function (data) {
$.each(data, function (i, part) {
map[part.description] = part;
parts.push(part.description);
});
typeahead.process(parts);
}
});
},
updater: function (item) {
selectedPart = map[item].itemNumber;
return item;
},
matcher: function (item) {
if (item.toLowerCase().indexOf(this.query.trim().toLowerCase()) != -1) {
return true;
}
},
sorter: function (items) {
return items.sort();
},
highlighter: function (item) {
var regex = new RegExp('(' + this.query + ')', 'gi');
return item.replace(regex, "<strong>$1</strong>");
}
});
Controller :
public ActionResult MakePartsArray(string query)
{
var possibleItem = query.ToLower();
var allItems = Db.PartInventorys.Where(l => l.ItemNumber.Contains(possibleItem)).Select(x => new { itemNumber = x.ItemNumber, description = x.Description });
return new JsonResult
{
ContentType = "text/plain",
Data = new { query, total = allItems.Count(), suggestions = allItems.Select(p => p.itemNumber).ToArray(), matches = allItems, },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};
}
In my controller I see the data being retrieved correctly and it appears to parse properly but nothing is showing up for my TypeAhead.
Any idea on how to verify exactly where the breakdown is occurring or does anyone see direct fault in my code?
Problem was in the ajax call-
$.ajax({
url: '#Url.Action("MakePartsArray")',
dataType: "json",
type: "POST",
data: {query: query},
success: function (data) {
$.each(data.matches, function (i, part) {
var composedInfo = part.description + ' (' + part.itemNumber + ')';
map[composedInfo] = part;
parts.push(composedInfo);
});
process(parts);
}
});
and in the controller on the return type
return new JsonResult
{
ContentType = "application/json",
Data = new { query, total = allItems.Count(), suggestions = allItems.Select(p => p.itemNumber).ToArray(), matches = allItems },
JsonRequestBehavior = JsonRequestBehavior.AllowGet
};

jquery CALLING TO Services! Services.invoke

This a service function "GetTaskProgress":
[WebMethod]
public IList<OrderViewDTO> GetTaskProgress(DateTime xDATEx)
{
try
{
return new OrderDataRepository()
.GetAllOrderData()
.Where(x => x.POD_DATE == xDATEx)
.GroupBy(o => o.User)
.Select(g => new OrderViewDTO
{
DriverId = g.Key.Id,
PdriverName = g.Key.Name,
OrderCount = g.Count(),
OrderCountWhereNameIsNotNull = g.Count(o => o.RECEIVE_NAME != null)
})
.ToList();
}
catch (Exception e)
{
throw WrapException(e);
}
}
This is the code of the jquery load button:
$('#LoadButton').click(function () {
var DateTime = $('#DateInput').val();
if (DateTime == '')
{
alert('PLEASE ENTER DATE');
}
else {
_Services.invoke({
method: 'GetTaskProgress',
data: { DateTime: DateTime },
success: function () {
alert(DateTime);
How do I call GetTaskProgress with a jQuery function that will pass the "date" into xDATEx?
at the moment when i click on the button i have the bug Invalid web service call, missing value for parameter: 'xDATEx
I'm not sure about _Services.invoke() (analogous to $.ajax() perhaps?), but you probably need to change your data parameter to match your service method parameter. Try this
_Services.invoke({
method: 'GetTaskProgress',
data: { xDATEx: DateTime },
success: function () {
alert(DateTime);
}
});

Resources