背景我们需要提交带有项目的模型。为此,我们建立了一个复杂的模型:
public class PaymentViewModel
{
public decimal? Payment { get; set; }
public string Description { get; set; }
public List<SplittedPaymentViewModel> SplittedPayment { get; set; } = new List<SplittedPaymentViewModel>();
}
public class SplittedPaymentViewModel
{
public short SplittedPaymentId { get; set; }
public decimal? Payment { get; set; }
public string Description { get; set; }
}
为了呈现html,我们有两个视图,一个是常规视图:CreatePayment
@model ZevApp.ViewModels.Record.PaymentViewModel
...
<input class="form-control" asp-for="Payment" type="number" />
<input class="form-control" asp-for="Description" />
...
<div class="panel-body" id="SplittedPayments">
@foreach (var spItem in Model.SplittedPayment)
{
@Html.Partial("SplittedPaymentPartial", spItem);
}
...
</div>
而另一个Partial:SplittedPaymentPartial
@model ZevApp.ViewModels.Record.SplittedPaymentViewModel
...
<input class="form-control" asp-for="Payment" type="number" />
<input class="form-control" asp-for="Description" />
...
如您所见,从第一个视图开始,我们称为部分视图,并将它们逐项传递给SplittedPayment列表。
意外行为我们运行了代码,但是意外地发生了行为:每个局部视图都将Payment和Description表单绑定到Parent PaymentViewModel父级,而不是从传递的项目中绑定?
有人知道错在哪里吗?
每个视图在文件的开头定义模型。
从控制器返回PaymentViewModel,为了进行测试,有树SplittedPaymentViewModel。但是我们看不到这些项目的价值。
我发现问题出在CreatePayment.cshtml(感谢MVC社区的人们)。调用部分视图时,它不提供有关spItem表达式的任何信息。
var savePrefix = ViewData.TemplateInfo.HtmlFieldPrefix;
for (var i = 0; i < Model.SplittedPayment.Count; i++)
{
ViewData.TemplateInfo.HtmlFieldPrefix = Html.NameFor(m => m.SplittedPayment[i]);
var spItem = Model.SplittedPayment[i];
@Html.Partial("SplittedPaymentPartial", spItem);
ViewData.TemplateInfo.HtmlFieldPrefix = savePrefix;
}
您可以在https://github.com/aspnet/Mvc/issues/4106上找到完整的描述
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句