简体   繁体   中英

Ajax data into MVC model

Our very simple models:

public class OrderSubmissionProductViewModel
{
    public int Id { get; set; }
    public decimal Price { get; set; }
    public int Qty { get; set; }
}

public class OrderSubmissionViewModel
{
    public int CustomerId { get; set; }
    public int AccountId { get; set; }

    public OrderSubmissionProductViewModel[] Products { get; set; }
}

The AJAX:

$.ajax({
    url: self.urlSubmitOrder,
    data: JSON.stringify({ submission: submission }),
    type: 'POST',
    success: function () { alert("Submitted"); },
    fail: function () { alert("Failed"); }
});

The MVC controller has this method signature:

public ActionResult SubmitAdminOrder(OrderSubmissionViewModel submission)
{ ... }

This is what the POST looks like:

{"submission":{"CustomerId":43,"AccountId":"20000","Products":[{"Id":4,"Price":100,"Qty":1},{"Id":6,"Price":14,"Qty":1}]}}

I can hit a breakpoint in the controller method, and the model is not null, but all of its properties are default values. It's not getting bound correctly. What am I doing wrong?

We're using ASP.Net MVC 4.

Make sure the submission object isn't empty and can you try adding a contentType to the ajax options?

$.ajax({
    url: self.urlSubmitOrder,
    data: JSON.stringify({ submission: submission }),
    type: 'POST',
    contentType: "application/json; charset=utf-8",
    success: function () { alert("Submitted"); },
    fail: function () { alert("Failed"); }
});

Or take a look at this post Pass viewmodel with two objects to controller using Json

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM