Ajax Post passing null to Controller

2019-07-15 15:16发布

I am making an AJAX POST request to an MVC controller, yet the data is coming through as null. I'm not sure why.

$(document).ready(function() {
  $("#btnSaveCustomer").click(function() {
    debugger; 
    var data = {
      _DcLink: "1",
      _Account: "Test",
      _Name: "TestName",
      _Title: "Mr",   
      _Init: "T"
    }

    $.ajax({
      method: "POST",
      url: '/Customer/SaveCustomer',
      data: JSON.stringify(data),
      success: function() {
        debugger;
        console.log(data)
        alert("Success")
      },
      error: function() {
        alert("Error")
      }
    });
})
public ActionResult SaveCustomer(string data)
{
  using (var ms = new MemoryStream(Encoding.UTF32.GetBytes(data)))
  {
    // Deserialization from JSON  
    DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(Customer));
    Customer serializeddata = (Customer)deserializer.ReadObject(ms);
  }
  return Json(new { Success = true });
}

No matter how I try to serialize the data it is always null. I believe the AJAX POST method is not executing properly

I am using dummy data in order to resolve the problem.

The code hits a breakpoint at MemoryStream in the controller - stating data is null.

System.ArgumentNullException: 'String reference not set to an instance of a String. Parameter name: s'

Any help appreciated

3条回答
smile是对你的礼貌
2楼-- · 2019-07-15 15:25

change like this;

data: {data : JSON.stringify(data)},
查看更多
淡お忘
3楼-- · 2019-07-15 15:32
$(document).ready(function() {
  $("#btnSaveCustomer").click(function() {
    debugger;
    var data = {
      _DcLink: "1",
      _Account: "Test",
      _Name: "TestName",
      _Title: "Mr",
      _Init: "T"
    }

    $.ajax({
      method: "POST",
      url: '/Customer/SaveCustomer',
      data: JSON.stringify(data),
      success: function(data) {
        debugger;
        console.log(data)
        alert("Success")
      },
      error: function() {
        alert("Error")
      }
    });
  })
查看更多
ら.Afraid
4楼-- · 2019-07-15 15:40

It's because the ModelBinder is expecting a property in the JSON named data, yet you're not sending that; all the properties are in the root object. That would work fine if you were binding to a model, but as you're not you need to amend the data structure in your JS slightly, to this:

var data = { 
  data: {
    _DcLink: "1",
    _Account: "Test",
    _Name: "TestName",
    _Title: "Mr",   
    _Init: "T"
  }
}
查看更多
登录 后发表回答