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

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


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 });}


If you need to send the FULL model to the controller, you first need the model to be available to your javascript code.

In our app, we do this with an extension method:

public static class JsonExtensions{    public static string ToJson(this Object obj)    {        return new JavaScriptSerializer().Serialize(obj);    }}

On the view, we use it to render the model:

<script type="javascript">  var model = <%= Model.ToJson() %></script>

You can then pass the model variable into your $.ajax call.


I have an MVC page that submits JSON of selected values from a group of radio buttons.

I use:

var dataArray = $.makeArray($("input[type=radio]").serializeArray());

To make an array of their names and values. Then I convert it to JSON with:

var json = $.toJSON(dataArray)

and then post it with jQuery's ajax() to the MVC controller

$.ajax({url: "/Rounding.aspx/Round/" + $("#OfferId").val(),type: 'POST',dataType: 'html',data: json, contentType: 'application/json; charset=utf-8',beforeSend: doSubmitBeforeSend,complete: doSubmitComplete,success: doSubmitSuccess});

Which sends the data across as native JSON data.

You can then capture the response stream and de-serialize it into the native C#/VB.net object and manipulate it in your controller.

To automate this process in a lovely, low maintenance way, I advise reading this entry that spells out most of native, automatic JSON de-serialization quite well.

Match your JSON object to match your model and the linked process below should automatically deserialize the data into your controller. It's works wonderfully for me.

Article on MVC JSON deserialization