Reputation: 4864
I tried an 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 received it in a controller (the method always invoked)
public ActionResult Check(AddressInfo addressInfo)
{
return Json(new { success = true });
}
Model here,
But when I tried to access (break point checked) the properties of the object (AddressInfo
) it always showed null
value. I tried without stringifying and stringifying. I 'm learning MVC now and a beginner. Please help
Upvotes: 1
Views: 10800
Reputation: 286
Try the following code:
return this.Json(new { success = true }, JsonRequestBehavior.AllowGet);
If this don't work just change the request parameter from AddressInfo
to String at the controller side.
This will definitely work!!
Upvotes: 1
Reputation: 60590
The reason this isn't working is because you're using ASP.NET MVC 2 and support for model binding from JSON wasn't added until ASP.NET MVC 3.
You can add that functionality to ASP.NET MVC 2 though. Phil Haack has a post describing that, with a link to sample code at the end: http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx
Upvotes: 1
Reputation: 40639
Add dataType
as json
in Ajax
and pass addressInfo
in data parameter
like,
$.ajax({
url: 'Check',
type: 'POST',
datatype:'json',
data: {addressInfo:kk},
success:function(data){
....
....
});
Upvotes: 0
Reputation: 1022
Try to pass data in querystring way like this:
$(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");
}
});
});
Upvotes: -1