Могут быть ситуации, когда может быть невозможно включить Doctype или метатег, или ничего не будет работать, как в моем случае, поэтому мне пришлось разобраться следующим образом, как объяснено.
Чтобы отправить объекты json обратно на сервер, необходимо будет поддерживать json.strinfy. Чтобы поддержать то же самое в IE, пожалуйста, скачайте json2.js с https://github.com/douglascrockford/JSON-js и обратитесь к вам. Следующий фрагмент кода работал для меня, я надеюсь, что это поможет кому-то еще.
//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>
Модель для списка адресов будет такой, как показано ниже. Обратите внимание, что имена свойств такие же, как у объекта addr, и он имеет get и set.
public class Address
{
public string HouseNo { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
}
Действие контроллера будет примерно таким, как показано ниже
[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;
}