I have a JQuery datatables code which is working in an old-school ASP.Net MVC project. However I couldn’t make it work in .Net Core 3.1. I tried almost every possible way but in best case I get null input in action method from the Ajax request. I logged the data in Ajax post method and it looks correct in the browser console.
This is the action method in my old project that works:
public ActionResult GetData()
{
string req = Request.Form[0].ToString();
...
}
This is the Ajax in my old project Datatables that works:
"ajax": {
"type": "POST",
"url": url,
"dataType": "json",
"data": function (d) {
d.searchParam = $('#srcParam').val();
return JSON.stringify(d);
}
I don’t know the equivalent of "Request.Form[0] in .Net Core which can catch the data without an input parameter. In my new project I used same Ajax but i always get null value coming into my action method’s input parameter. I tried many possible fixes including below but nothing worked:
-Adding [HttpPost]
attribute to my action method
-Adding contentType: "application/json"
to my ajax
-Using ajax type: "GET"
instead.
-Naming my data in ajax data: { data: JSON.stringify(@Model.CityId) },
and having same name input parameter as "data" in my action method.
-Adding [FromBody]
and [FromForm]
attributes to my action method input parameter.
-Tried to send data with and without JSON.stringify
At this point I am lost and don’t know how to get this data. For the reference current state of the code i have in my current project is below:
Action method
[HttpPost]
public JsonResult GetBusRouteList([FromBody]string data)
{
string req = data;
}
Ajax
"ajax": {
"type": "POST",
"url": url,
"dataType": "json",
"contentType": "application/json",
"data" : { data: JSON.stringify(@Model.CityId) }
}
2
Answers
You can change your datatable ajax and action like this:
Action:
Ajax:
You can also refer to the examples of the link
Update:
replace ‘Request.Form[0].ToString();’ in ASP .Net Core
Change your code like below:
Action method:
Ajax: