我有一个像这样的表格:
<form id="orderForm">
<input name="Customer" value="Mr.Test" />
<input name="ProductLines" value='[{"Product":{"Name":"Orange","Price":"10"},"amount":"2","total":"20"}, {"Product":{"Name":"Apple","Price":"5"},"amount":"3","total":"15"}]' />
</form>
和具有视图模型的控制器:
[HttpPost]
public ActionResult Save(OrderViewModel vm)
{
//...
}
public class OrderViewModel
{
public OrderViewModel() { ProductLines = new List<OrderProductViewModel>(); }
public string Customer { get; set; }
public IEnumerable<OrderProductViewModel> ProductLines { get; set; }
}
public class OrderProductViewModel
{
public ProductViewModel Product { get; set; }
public int Amount { get; set; }
public int Total { get; set; }
}
public class ProductViewModel
{
public string Name { get; set; }
public int Price { get; set; }
}
是否可以使用jquery
发布此表单 $.post('@Url.Action("Save")', $("#orderForm").serialize(), function (data) {//...}, "json");
并在服务器端填写ProductLines集合。 (目前它总是空的)
谢谢!
答案 0 :(得分:2)
发布对象需要在json对象中转换,并使用内容类型json发布。 尝试以下它可能会有所帮助
var results = {};
$.each($("#orderForm").serializeArray(), function (index, item) {
results[item.name] = item.value;
});
results.ProductLines = $.parseJSON(results.ProductLines);
$.ajax({
url: '@Url.Action("Save")',
type: 'post',
data: JSON.stringify(results),
contentType: "application/json; charset=utf-8",
dataType:'json',
success: function (data) {
alert("hi");
}
});