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

Viewed 3217

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;
}
2 Answers

May be a trivial issue but I overlooked it and had spent a few hours trying to debug this issue.

Make sure your model that you're binding has its properties labelled as public.

Related