传递JSON名单MVC 3 [英] Passing json list to MVC 3
问题描述
我试图用Ajax提交给MVC3控制器:
I am trying to submit this with Ajax to a 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'); }
});
现在这已经去到像这样的控制器:
Now this has to go to the controller like so:
[HttpPost]
public Boolean Save(Int32 productId, Object[] specifications)
{
return true;
}
不过,对象[]不起作用,返回null,我试过各种东西,像模特的名单等,但它会留下空。
But Object[] does not work, returns null, I tried all sorts of stuff like lists of a model etc, but it will stay null.
如何解决呢?
推荐答案
ASP.NET MVC 3包含内置JSON模型绑定。
ASP.NET MVC 3 includes built-in JSON model binding.
所以创造出相匹配的JSON你试图提交简单波苏斯:
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)
只要在JSON对象的属性名称匹配POCO的属性名称,MVC将束缚你。
As long as the property names in the JSON object match the property names in the POCO's, MVC will bind for you.
此外 - 你应该使用 .stringify
或类似的东西连载的JSON和的设置的contentType
$。阿贾克斯
对象相应。
Also - you should serialise the JSON using .stringify
or something similar, and set the contentType
of the $.ajax
object accordingly.
这篇关于传递JSON名单MVC 3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!