I am struggling to post json data to asp mvc controller method from ajax request but asp mvc model binder is not binding it because of some unknown reasons.
I have tried to follow multiple answers posted here on SO including below
Post json object to ASP MVC doesn't work properly
but my jQuery ajax method always posts null values to asp mvc controller.
Basically, I am trying to load an partial view via ajax request.
Ajax Request
var myData =
{
"Id": 7,
"Name": "Name 1"
};
var obj = { 'test': myData };
var val = JSON.stringify(obj);
console.log(val);
$.ajax({
type: 'POST',
dataType: 'html',
url: '/Home/Partial',
contentType: 'application/json',
data: val,
success: function (xhr, status, response) {
console.log(response);
$('#1').html(response.responseText);
},
error: function (err) {
alert("error - " + err);
}
});
Controller Method
[HttpPost]
public IActionResult Partial(Test test)
{
return PartialView("_Test", test);
}
Model
public class Test
{
public int Id;
public string Name;
}
data: myData. You're adding another object property in the values you're sending which is confusing the ModelBindertest. That's not needed. Ifdata: myDatadidn't work step through the request in VS. If you don't even get that far, check the console to find out what the error is in JSpublic IActionResult Partial([FromBody]Test test)so the model binder knows to check the body for the model.[FromBody].