Proper way to use AJAX Post in jquery to pass model from strongly typed MVC3 view Proper way to use AJAX Post in jquery to pass model from strongly typed MVC3 view jquery jquery

Proper way to use AJAX Post in jquery to pass model from strongly typed MVC3 view


I found 3 ways to implement this:

C# class:

public class AddressInfo {    public string Address1 { get; set; }    public string Address2 { get; set; }    public string City { get; set; }    public string State { get; set; }    public string ZipCode { get; set; }    public string Country { get; set; }}

Action:

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

JavaScript you can do it three ways:

1) Query String:

$.ajax({    url: '/en/Home/Check',    data: $('#form').serialize(),    type: 'POST',});

Data here is a string.

"Address1=blah&Address2=blah&City=blah&State=blah&ZipCode=blah&Country=blah"

2) Object Array:

$.ajax({    url: '/en/Home/Check',    data: $('#form').serializeArray(),    type: 'POST',});

Data here is an array of key/value pairs :

=[{name: 'Address1', value: 'blah'}, {name: 'Address2', value: 'blah'}, {name: 'City', value: 'blah'}, {name: 'State', value: 'blah'}, {name: 'ZipCode', value: 'blah'}, {name: 'Country', value: 'blah'}]

3) JSON:

$.ajax({      url: '/en/Home/Check',      data: JSON.stringify({ addressInfo:{//missing brackets          Address1: $('#address1').val(),          Address2: $('#address2').val(),          City: $('#City').val(),          State: $('#State').val(),          ZipCode: $('#ZipCode').val()}}),      type: 'POST',      contentType: 'application/json; charset=utf-8'});

Data here is a serialized JSON string. Note that the name has to match the parameter name in the server!!

='{"addressInfo":{"Address1":"blah","Address2":"blah","City":"blah","State":"blah", "ZipCode", "blah", "Country", "blah"}}'


You can skip the var declaration and the stringify. Otherwise, that will work just fine.

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


This is the way it worked for me:

$.post("/Controller/Action", $("#form").serialize(), function(json) {               // handle response}, "json");[HttpPost]public ActionResult TV(MyModel id){    return Json(new { success = true });}