Aleks Andreev
Aleks Andreev

Reputation: 7054

Customize jQuery JSON serialization

In my ASP.MVC I have following models:

public class MySubModel
{
  public int Id { get; set; }
}

public class MyModel
{
  public List<MySubModel> Items { get; set; }
}

On the client side I'm using jQuery.ajax() to send data to the server via POST request. My problem is that each Id in the list has it default value (0).

After debugging through DefaultModelBinder I figured out that ASP.MVC expect keys like this:

Items[0].Id

while jQuery send

Items[0][Id]

Is there a way to customize this jQuery behavior?

P.S. It's look like I can use JSON.stringify() on the client and some JSON parser on the server but it's a hack for me. Is there a better way?

Upvotes: 0

Views: 57

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038850

P.S. It's look like I can use JSON.stringify() on the client and some JSON parser on the server but it's a hack for me. Is there a better way?

JSON.stringify is sufficient, you don't need any JSON parser on the server, that's already handled by the underlying framework for you.

Example:

var model = { items: [] };
// now add some elements to the items array
model.items.push({ id: 1 });
model.items.push({ id: 2 });
model.items.push({ id: 3 });
...

$.ajax({
    url: 'your controller action endpoint comes here',
    method: 'post',
    contentType: 'application/json',
    data: JSON.stringify(model),
    success: function(result) {
        // do something with the results here
    }
});

which will successfully send to the following action:

[HttpPost]
public ActionResult SomeAction(MyModel model)
{
    ... use your model here directly without any JSON parsing
}

The 2 important parameters of your AJAX request are the following:

contentType: 'application/json',
data: JSON.stringify(model)

and of course the model javascript variable should reflect your server side view model structure as shown here (it should have an items array property of elements having an id property).

Upvotes: 3

Related Questions