Making Json Object Post to Server in Asp.NET, Problem in IE.
I am copying my own post from StackOverflow.
There may be situations where it may not be possible to include the Doctype or meta tag or nothing might work as in my case so I had to figure out this way below as explained.
To post json objects back to the server, json.strinfy will have to be supported. To support the same on IE, please download json2.js from https://github.com/douglascrockford/JSON-js and refer in your view. The following code snipped worked for me, I hope it helpe someone else too.
//include jquery library from your preferred cdn or local drive.
<!-- include json2.js only when you need JSON.stringfy method -->
<script type="text/javascript" src="~/scripts/json2.js"></script>
<script type="text/javascript">
function button_click() {
//object to post back to the server.
var postData = { "Id": $('#hfUserId').val(), "Name": $('#Name').text(),
"address": new Array() };
var address = new Array(); var addr;
addr = { "HouseNo": "1", "Street": "ABC", "City": "Chicago", "State": "IL" };
address[0] = addr;
addr = { "HouseNo": "2", "Street": "DEF", "City": "Hoffman Est", "State": "IL" };
address[1] = addr;
//make ajax call to server to save the data
$.ajax({
url: '@Url.Action("myAction", "MyController")',
type: 'POST',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(postData),
async: true,
success: function (data) { alert('User Saved'); },
error: function (data) { alert('Could not save User'); }
});
}
</script>
The model for the address list will be as below. Please note that the property names are the same as the addr object and it has get and set.
public class Address
{
public string HouseNo { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
}
The controller action will be something like below
[HttpPost]
public ActionResult myAction(string Id, string Name, List<Address> address)
{
JsonResult result = null;
result = new JsonResult
{
Data = new
{
error = false,
message = "User Saved !"
}
};
return result;
}
No comments:
Post a Comment