0

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?

1
  • show your client side code Commented May 2, 2016 at 13:24

1 Answer 1

3

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).

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.