将json列表传递给MVC 3

Rog*_*Far 5 jquery asp.net-mvc-3

我试图用Ajax将它提交给MVC3控制器:

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

    $.each($('.specificationId'), function () {
        var specId = $(this).attr('id').replace('specification_', '');

        var specification = {
            specificationId: specId,
            articleId: $('#articleid_' + specId).attr('value'),
            price: $('#price_' + specId).attr('value'),
            stock: $('#stock_' + specId).attr('value'),
            stockCount: $('#stockcount_' + specId).attr('value'),
            weight: $('#weight_' + specId).attr('value'),
            visible: $('#visible_' + specId).attr('checked')
        };

        params.list.add(specification);
    });

    console.log(params);
    //all values are parsed fine here, shows an array with json objects

    $.ajax({
        type: "POST",
        url: "/Admin/Product/Save/",
        data: params,
        success: function () { alert('done'); }
    });
Run Code Online (Sandbox Code Playgroud)

现在这必须像这样去控制器:

    [HttpPost]
    public Boolean Save(Int32 productId, Object[] specifications)
    {

        return true;
    }
Run Code Online (Sandbox Code Playgroud)

但是Object []不起作用,返回null,我尝试了各种各样的东西,比如模型列表等,但是它会保持为null.

如何解决这个问题?

gra*_*ram 6

尝试将控制器操作更改为(我在此假设规范是表示您尝试发布的JSON的模型):

public Boolean Save(Int32 productId, List<Specification> specifications)
Run Code Online (Sandbox Code Playgroud)

然后在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'); }
});
Run Code Online (Sandbox Code Playgroud)


RPM*_*984 6

ASP.NET MVC 3包含内置的JSON模型绑定.

因此,创建与您尝试提交的JSON匹配的简单POCO:

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; }
}
Run Code Online (Sandbox Code Playgroud)

然后在你的行动中接受:

[HttpPost]
public Boolean Save(ProductJsonModel model)
Run Code Online (Sandbox Code Playgroud)

只要JSON对象中的属性名称与POCO中的属性名称匹配,MVC就会为您绑定.

此外-你应该连载使用JSON .stringify或类似的东西,并设置contentType了的$.ajax对象相应.