後端我有這樣這樣的控制器:提交元素的JSON列表MVC 5控制器導致空指針異常
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"}}
現在,我嘗試了許多不同的C ombinations但仍然得到「對象引用未設置爲對象的實例」。在下面幾行
foreach (var product in mixsearch.elems)
很明顯的是,控制器不正確反序列化的有效載荷,這個問題無法理解如何提交使用jQuery和JSON對象列表。
任何人都可以點亮這個?
它看起來並不像你有事情正確匹配。在你的c#對象中,MixSearch是一個數組,但是你的請求有效負載將'MixSearch'部分作爲一個對象。索引是否正確? – peinearydevelopment