Passing json list to MVC 3

后端 未结 3 1753
时光取名叫无心
时光取名叫无心 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: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.

提交回复
热议问题