ASP.NET MVC模型内嵌List提交后为null问题求助
问题解决:MVC表单提交后集合列表为null
问题原因
ASP.NET MVC的默认模型绑定器需要集合元素的表单name属性包含索引标识(如discounts[0].Discount),才能将表单值映射到模型的List集合中。你当前使用foreach循环渲染列表项,生成的表单元素name属性是deets.Discount这类无索引的格式,绑定器无法识别这些值属于discounts列表,因此提交后列表为null。
解决方案1:使用for循环替代foreach循环
修改视图中的列表渲染部分,通过索引遍历List集合,让表单元素生成带索引的name属性:
<div class="container-fluid form-horizontal"> <h4>Details for @Model.CustomerName </h4> @Html.HiddenFor(model => model.CustomerId) @* 替换foreach为for循环 *@ @for (int i = 0; i < Model.discounts.Count; i++) { <div class="row form-group"> <div class="col-md-6"> @Html.DisplayFor(model => model.discounts[i].CategoryName) </div> @Html.HiddenFor(model => model.discounts[i].TradeCustomerId) @Html.HiddenFor(model => model.discounts[i].CategoryGroupIdentifier) <div class="col-md-6"> @Html.EditorFor(model => model.discounts[i].Discount, new { htmlAttributes = new { @class = "form-control" } }) </div> </div> } </div>
这样生成的表单元素name属性会是discounts[0].TradeCustomerId、discounts[0].Discount、discounts[1].TradeCustomerId等格式,模型绑定器就能正确将这些值填充到tradeCustomerDetails.discounts列表中。
解决方案2:使用EditorTemplate(更优雅的方式)
- 在
Views/Shared/EditorTemplates目录下创建TradeDiscount.cshtml文件(文件名需与模型类名一致),内容如下:
@model Trade_Counter.Models.TradeDiscount <div class="row form-group"> <div class="col-md-6"> @Html.DisplayFor(model => model.CategoryName) </div> @Html.HiddenFor(model => model.TradeCustomerId) @Html.HiddenFor(model => model.CategoryGroupIdentifier) <div class="col-md-6"> @Html.EditorFor(model => model.Discount, new { htmlAttributes = new { @class = "form-control" } }) </div> </div>
- 主视图中替换原来的foreach循环为:
<div class="container-fluid form-horizontal"> <h4>Details for @Model.CustomerName </h4> @Html.HiddenFor(model => model.CustomerId) @Html.EditorFor(model => model.discounts) </div>
MVC会自动遍历discounts列表,使用EditorTemplate渲染每个元素,并生成带索引的name属性,实现正确的模型绑定。
内容的提问来源于stack exchange,提问作者Jim Tench
相关产品推荐
相关产品推荐

