[英]Data from Partial view is NULL
我有部分看法:
@model BasicFinanceUI.Models.TransactionLine
<div class="form-group">
<label for="cmbCategory0" class="col-lg-1 control-label">Category:</label>
<div class="col-lg-3">
@Html.DropDownListFor(x => x.CategoryId,
new SelectList(Model.References.Categories, "Value", "Text", Model.CategoryId), "Select one",
new { @onchange = "populateSubCategory(0)", @class = "cmbCategory form-control" })
</div>
</div>
这个局部视图是从我的主视图上的对象的List <>加载的:
@foreach (var line in Model.Transaction.TransactionLines)
{
@Html.Partial("_TransactionLine", line)
}
局部视图已正确加载,并带有正确的数据。
但是,当我要保存数据时-列表中似乎有一行,但该行中没有数据。 我是部分视图的新手,但是MVC似乎没有将部分视图数据映射到创建部分视图列表的List <>。
难道我做错了什么?
在控制器中,当我尝试将数据读入对象以将它们发送回数据库时,我正在这样做:
item.TransactionLines = new List<TransactionLineDto>();
foreach (var line in model.Transaction.TransactionLines)
{
item.TransactionLines.Add(new TransactionLineDto
{
Id = line.Id,
CostCentreId = line.CostCentreId,
SubCategoryId = line.SubCategoryId,
TransactionId = model.Transaction.Id,
Amount = line.Amount
});
}
但是,我发现所有值都是0。似乎局部视图不会将数据返回到视图模型。 那是预期的行为,还是我做错了什么?
我尝试了“ Partial”和“ RenderPartial”。 但是不确定为什么是正确的,因为它们都会导致相同的问题。
如果检查HTML,则将看到该部分内的下拉列表的名称属性为CategoryId
。 这是错误的,因为它应该类似于Transaction.TransactionLines[0].CategoryId
。 否则,ASP.NET MVC将无法正确将值映射到模型。 解决此问题的最简单方法是使用for循环并在主视图内移动部分视图HTML。
for (int i = 0; i < model.Transaction.TransactionLines.Count; i++)
{
<div class="form-group">
<label for="cmbCategory0" class="col-lg-1 control-label">Category:</label>
<div class="col-lg-3">
@Html.DropDownListFor(x => x.Transaction.TransactionLines[i].CategoryId,
new SelectList(x.Transaction.TransactionLines[i].References.Categories, "Value", "Text", x.Transaction.TransactionLines[i].CategoryId), "Select one",
new { @onchange = "populateSubCategory(0)", @class = "cmbCategory form-control" })
</div>
</div>
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.