Reputation: 127
(I'm using ASP.NET Core razor pages) I have a JsonResult method:
public JsonResult OnPostloadListJson()
{
vwOpenRequests = _context.vwOpenRequests.ToList();
return new JsonResult(vwOpenRequests);
//var items = _context.vwOpenRequests.ToList();
//IList<vwOpenRequest> resultList = new List<vwOpenRequest>();
//for (int i = 0; i < items.Count(); i++)
//{
// resultList.Add(items[i]);
//}
//return new JsonResult(resultList);
}
Which I need pulled in via ajax call, for a DataTable:
$(document).ready(function () {
$('#mytable').DataTable({
processing: true,
serverSide: true,
ajax: {
//url: "?handler=loadListJson",
url: "@Url.Page("/Index")?handler=loadListJson",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function (xhr) {
xhr.setRequestHeader("RequestVerificationToken",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
error: function (xhr, status, error) {
alert(error);
}
},
columns: [
{ data: "RequestTo" },
{ data: "SubGroup" },
{ data: "RequestDt" },
{ data: "DueDt" },
{ data: "Desc" },
{ data: "Reason" },
{ data: "LastUpdateDt" },
{ data: "RequestType" }
]
});
});
This results in this error: "SyntaxError: Unexpected token < in JSON at position 0" which led me to look at the JSON response being received... it's the HTML page for some reason, and my content-type is being defined as "text/html" as a result.
My table includes < thead > and < tr > elements with headers, amounting in the same number of columns I'm attempting to pull. I've added a breakpoint to my JsonResult method and it isn't hitting it before throwing the error, even though my handler and url are properly named. What am I missing here?
Upvotes: 0
Views: 833
Reputation: 7180
I tested your code and the same problem as yours appeared. After testing, I found that your code has three problems.
1:Routing
In your post action,your method should be OnPostLoadListJson
instead of OnPostloadListJson
,l
should be capitalized.
In your ajax,url
should be url: "?handler=loadListJson",
2:Modify your post method like below:
public JsonResult OnPostLoadListJson()
{
vwOpenRequests = _context.vwOpenRequests.ToList();
return new JsonResult(new { data = vwOpenRequests });
}
3:columns in your ajax should be:
columns: [
{ data: "requestTo" },
{ data: "subGroup" },
{ data: "requestDt" },
{ data: "dueDt" },
{ data: "desc" },
{ data: "reason" },
{ data: "lastUpdateDt" },
{ data: "requestType" }
]
The first letter of data should be lowercase.
Upvotes: 1