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;
}
myData
would have been enough to bind the object.
var myData = { Id: 7, Name: "Name 1" };
var val = JSON.stringify(myData);
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);
}
});
You should also consider [FromBody]
attribute on the parameter so the model binder knows to check the body for the model.
[HttpPost]
public IActionResult Partial([FromBody]Test test) {
return PartialView("_Test", test);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With