【发布时间】:2016-03-07 19:47:06
【问题描述】:
我正在尝试实现一个复杂的视图模型并将其绑定到一个表单。不幸的是,绑定似乎丢弃/错过了子模型前缀,因此当我尝试将模型提交回来时,模型绑定器不知道如何解释数据。这是代码的简化版本...
父模型
public class MainVM
{
public bool MainProperty1 { get; set; }
public ChildVM ChildModel { get; set; }
}
童模
public class ChildVM
{
public int ChildProperty1 { get; set; }
public string ChildProperty2 { get; set; }
public string ChildProperty3 { get; set; }
}
index.cshtml
@model MainVM
<form id="main-form" asp-controller="main" asp-action="submit" method="post">
<div>
@await Html.PartialAsync("partial", Model.ChildModel)
</div>
</form>
partial.cshtml
@model ChildVM
<div>
<input asp-for="ChildProperty1" />
<input asp-for="ChildProperty2" />
<input asp-for="ChildProperty3" />
</div>
输出
<form id="main-form" method="post" action="/main/submit">
<div>
<div>
<input type="text" data-val="true" name="ChildProperty1" data-val-maxlength-max="17" data-val-minlength-min="4" id="ChildProperty1" />
<input type="text" data-val="true" name="ChildProperty2" data-val-maxlength-max="50" data-val-minlength-min="3" id="ChildProperty2" />
<input type="text" data-val="true" name="ChildProperty3" data-val-maxlength-max="50" data-val-minlength-min="3" id="ChildProperty3" />
</div>
</div>
</form>
如您所见,name 属性上的绑定缺少ChildVM 的前缀(例如name="ChildVM.ChildProperty1")我的问题是为什么会删除或丢失它?不确定我错过了什么,或者这是否是 MVC6 的事情,因为据我所知,这应该可以工作?
谢谢
【问题讨论】:
标签: viewmodel model-binding asp.net-core-mvc