gpt4 book ai didi

jquery - 将 json 列表传递给 MVC 3

转载 作者:行者123 更新时间:2023-12-03 22:56:56 25 4
gpt4 key购买 nike

我正在尝试使用 Ajax 将其提交到 MVC3 Controller :

    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'); }
});

现在必须像这样转到 Controller :

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

return true;
}

但是 Object[] 不起作用,返回 null,我尝试了各种东西,例如模型列表等,但它将保持 null。

如何解决这个问题?

最佳答案

ASP.NET MVC 3 包含内置 JSON 模型绑定(bind)。

因此,创建与您尝试提交的 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; }
}

然后在你的行动中接受这一点:

[HttpPost]
public Boolean Save(ProductJsonModel model)

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

此外 - 您应该使用 .stringify 或类似的方法序列化 JSON,并相应地设置 $.ajax 对象的 contentType

关于jquery - 将 json 列表传递给 MVC 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6405543/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com