Passing json list to MVC 3

后端 未结 3 1742
时光取名叫无心
时光取名叫无心 2021-01-05 22:02

I am trying to submit this with Ajax to a MVC3 controller:

    var params = {
        \'productId\': productId,
        \'list\': []
    };

    $.each($(\'.         


        
相关标签:
3条回答
  • 2021-01-05 22:53

    Try changing your controller action to (I'm assuming here that Specification is a model representing the JSON you're trying to post):

    public Boolean Save(Int32 productId, List<Specification> specifications)
    

    And then change these things in your JS:

    var params = {
        'productId': productId,
        'specifications': []
    };
    
    params.specifications.add(specification);
    
    $.ajax({
        type: "POST",
        url: "/Admin/Product/Save/",
        data: JSON.stringify(params),
        contentType: 'application/json',
        success: function () { alert('done'); }
    });
    
    0 讨论(0)
  • 2021-01-05 22:53

    jQuery .ajax() converts the JSON object to a collection of key value pairs in the application/x-www-form-urlencoded content type. You can read a good explanation of this in the blog post and comments of POSTing JSON Data to MVC Controllers

    So, You should either create a custom ModelBinder or put FormCollection form as the parameter instead of Object[]. The FormCollection will give you a NameValueCollection of the Form's values that also implements IValueProvider. You can loop through the collection and all your data will be there.

    0 讨论(0)
  • 2021-01-05 22:59

    ASP.NET MVC 3 includes built-in JSON model binding.

    So create simple POCOs which matches the JSON your attempting to submit:

    public class ProductJsonModel
    {
       public int ProductId { get; set; }
       public ProductSpecificationJsonModel[] @List { get; set; }
    }
    
    public class ProductSpecificationJsonModel
    {
       public int SpecificationId { get; set; }
       public int ArticleId { get; set; }
       public double Price { get; set; }
       public int Stock { get; set; }
       public int StockCount { get; set; }
       public int Weight { get; set; }
       public bool Visible { get; set; }
    }
    

    Then accept that in your action:

    [HttpPost]
    public Boolean Save(ProductJsonModel model)
    

    As long as the property names in the JSON object match the property names in the POCO's, MVC will bind for you.

    Also - you should serialise the JSON using .stringify or something similar, and set the contentType of the $.ajax object accordingly.

    0 讨论(0)
提交回复
热议问题