How to send a model in jQuery $.ajax() post request to MVC controller method

ravikiran picture ravikiran · Oct 5, 2009 · Viewed 155.5k times · Source

In doing an auto-refresh using the following code, I assumed that when I do a post, the model will automatically sent to the controller:

$.ajax({
    url: '<%=Url.Action("ModelPage")%>',
    type: "POST",
    //data:  ??????
    success: function(result) {
        $("div#updatePane").html(result);
    },

    complete: function() {
    $('form').onsubmit({ preventDefault: function() { } });

    }
});

Every time there is a post, I need to increment the value attribute in the model:

public ActionResult Modelpage(MyModel model)
    {                   
        model.value = model.value + 1;

        return PartialView("ModelPartialView", this.ViewData);
    }

But the model is not passed to the controller when the page is posted with jQuery AJAX request. How can I send the model in the AJAX request?

Answer

Chris S picture Chris S · Oct 27, 2011

The simple answer (in MVC 3 onwards, maybe even 2) is you don't have to do anything special.

As long as your JSON parameters match the model, MVC is smart enough to construct a new object from the parameters you give it. The parameters that aren't there are just defaulted.

For example, the Javascript:

var values = 
{
    "Name": "Chris",
    "Color": "Green"
}

$.post("@Url.Action("Update")",values,function(data)
{
    // do stuff;
});

The model:

public class UserModel
{
     public string Name { get;set; }
     public string Color { get;set; }
     public IEnumerable<string> Contacts { get;set; }
}

The controller:

public ActionResult Update(UserModel model)
{
     // do something with the model

     return Json(new { success = true });
}