后端我有一个像这样的控制器:
public class MixSearch
{
public int quantity { get; set; }
public int um { get; set; }
public string search { get; set; }
}
public class JsonPostMixSearch
{
public int index { get; set; }
public MixSearch[] elems { get; set; }
}
public class MixController : Controller
{
ApplicationDbContext db = new ApplicationDbContext();
[HttpPost]
public ActionResult Best(JsonPostMixSearch mixsearch)
{
List<Mix> mixes = new List<Mix>();
Mix lowest = new Mix { Products = new List<Product>(), Total = 0 };
mixes.Add(lowest);
List<List<Product>> matrix = new List<List<Product>>();
foreach (var product in mixsearch.elems)
{
List<Product> products = new List<Product>();
foreach (var term in product.search.Split(' '))
{
var query = db.Products.Where(p => p.Description.Contains(term)).OrderBy(p => p.Price/p.Quantity).Take(4).ToList();
products.AddRange(query);
lowest.Products.Add(query.First());
lowest.Total += query.First().Price * product.quantity;
}
matrix.Add(products);
}
return View(mixes);
}
}
前端我使用jquery从页面中以前添加的元素创建正确的数据:
$("#calcolamix").click(function (e) {
var mix = new Object();
$(".productsearch").each(function (index) {
var input = $(this);
mix[index] = { quantity: input.data("quantity"), um: input.data("um"), search: input.data("search") }
});
$.ajax({
url: "@Url.Action("Best","Mix")",
type: "POST",
data: JSON.stringify(mix),
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (response) {
$("#mixresult").html(response.responseText);
},
success: function (response) {
$("#mixresult").html(response);
}
});
});
请求有效负载如下
{0: {quantity: 1, um: 1, search: "acqua"}}
现在,我尝试了许多不同的组合,但仍然得到了#34;对象引用未设置为对象的实例。&#34;在以下几行
foreach (var product in mixsearch.elems)
很明显,控制器没有正确地反序列化有效负载,问题是无法理解如何使用jquery和JSON提交对象列表。
任何人都可以对此有所了解吗?
答案 0 :(得分:0)
反序列化不起作用,因为ASP.NET MVC中的模型绑定器无法将传入数据映射到JsonPostMixSearch
类型。您应该在名为mix
的{{1}}对象中创建一个数组,并将元素添加到该数组中。此外,您还应在elems
上设置index
属性:
mix