Always get null values ​​in controller for ajax message

I tried the ajax post from my view as shown below (using jQuery).

Complete solution here.

$(document).ready(function () { var kk = { Address1: "423 Judy Road", Address2: "1001", City: "New York", State: "NY", ZipCode: "10301", Country: "USA" }; console.log(JSON.stringify(kk)); $.ajax({ url: 'Check', type: 'POST', data: JSON.stringify(kk), dataType:"json", contentType: 'application/json; charset=utf-8', success: function (data) { alert(data.success); }, error: function () { alert("error"); } }); }); 

And got it in the controller (the method is always called)

 public ActionResult Check(AddressInfo addressInfo) { return Json(new { success = true }); } 

The model is here , But when I tried to access (check the breakpoint), the properties of the object ( AddressInfo ) always displayed null . I tried, not pulling and pulling. Now I'm learning MVC and getting started. Please, help

+1
source share
4 answers

The reason this does not work is because you are using ASP.NET MVC 2 and support for model binding from JSON was not added until ASP.NET MVC 3.

You can add this functionality to ASP.NET MVC 2. Phil Haack has a post describing this, with a link to the sample code at the end: http://haacked.com/archive/2010/04/15/sending-json-to -an-asp-net-mvc-action-method-argument.aspx

+1
source

Try using the following code:

 return this.Json(new { success = true }, JsonRequestBehavior.AllowGet); 

If this does not work, just change the request parameter from AddressInfo to String on the controller side. It will definitely work!

+1
source

Try passing the data in the order of the request as follows:

  $(document).ready(function () { var data = "Address1=423 Judy Road&Address2=1001&City=New York&State=NY&ZipCode=10301&Country=USA"; $.ajax({ url: 'Check', type: 'POST', data: data, contentType: 'application/json; charset=utf-8', success: function (data) { alert(data.success); }, error: function () { alert("error"); } }); }); 
0
source

Add dataType as json in Ajax and go addressInfo in data parameter as,

 $.ajax({ url: 'Check', type: 'POST', datatype:'json', data: {addressInfo:kk}, success:function(data){ .... .... }); 
0
source

Source: https://habr.com/ru/post/1332151/


All Articles