Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind an object to asp mvc controller from ajax request using asp.net core and Jquery

Tags:

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;
}
like image 860
PalakM Avatar asked Jul 26 '17 15:07

PalakM


1 Answers

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);
}
like image 82
Nkosi Avatar answered Oct 11 '22 14:10

Nkosi