[英]Why doesn't this model binding work?
我知道HtmlHelper中名称的方式破坏了模型绑定。 但是我还没有弄清楚如何解决它。 或者,即使有修复程序。
一点解释。 我正在使用一种模型来填充:文本,控件,默认值(选择列表)和保存的值。 我正在使用另一个ViewModel仅返回:value,dataid和ctrltypeid。 已注释掉的是导致未填充回发ViewModel的代码(例如:Html.TextBoxFor)。 工作代码(例如:Html.TextBox)按预期方式工作。 因此,我想知道对注释的代码该怎么做才能使其像未注释的代码一样工作。 实际上我能做些什么吗?
@model InspectionWebFormsMVC.ViewModels.FormRowModel
@using (Html.BeginForm("Index", "Section", FormMethod.Post))
{
<div style="clear:both; padding:1%;">
<div class="section">
@Model.Section
</div>
<div class="number">
@Model.SectionNumber
</div>
<div class="desc">
@Model.Description
</div>
<div class="ctrl">
@{
int i = 0;
//for (int i = 0; i < formRow.RowInput.Count; ++i)
foreach (var RowInput in Model.RowInput)
{
var ddv = new SelectList(RowInput.RowCtrl.DefaultValues, "Value", "Label");
switch (RowInput.RowCtrl.Type)
{
case "dropdown":
//@Html.DropDownListFor(blah => RowInput.InputtedData, ddv)
//@Html.HiddenFor(blah => RowInput.InputtedDataID)
//@Html.HiddenFor(blah => RowInput.RowCtrl.CtrlTypeID)
@Html.DropDownList("InputtedData", ddv)
@Html.Hidden("InputtedDataID", RowInput.InputtedDataID)
@Html.Hidden("CtrlTypeID", RowInput.RowCtrl.CtrlTypeID)
<br />
break;
case "text":
//@Html.TextBoxFor(blah => RowInput.InputtedData)
//@Html.HiddenFor(blah => RowInput.InputtedDataID)
//@Html.HiddenFor(blah => RowInput.RowCtrl.CtrlTypeID)
@Html.TextBox("InputtedData", RowInput.InputtedData)
@Html.Hidden("InputtedDataID", RowInput.InputtedDataID)
@Html.Hidden("CtrlTypeID", RowInput.RowCtrl.CtrlTypeID)
<br />
break;
}
}
++i;
}
显然是Viewmodel用于回发。
namespace InspectionWebFormsMVC.ViewModels
{
public class SaveKeyValueInput
{
public long InputtedDataID { get; set; }
public long CtrlTypeID { get; set; }
public string InputtedData { get; set; }
}
}
从控制器。 用于测试。
[HttpPost]
public ActionResult Index(SaveKeyValueInput placeholder)
{
var ha = placeholder;
var la = "Hello";
FormRowProcessing placeholder2 = new FormRowProcessing();
var stub = placeholder2.stub()[2];
return View(stub);
}
这是使注释的代码起作用的方法:
for (int i = 0; i < Model.RowInput.Count; i++)
{
@Html.DropDownListFor(blah => blah.RowInputpi[i].InputtedData, ddv)
@Html.HiddenFor(blah => blah.RowInput[i].InputtedDataID)
@Html.HiddenFor(blah => blah.RowInput[i].RowCtrl.CtrlTypeID)
...
}
或更好的方法是完全摆脱这个丑陋的循环(for或foreach),并用一行代码替换它:
@Html.EditorFor(x => x.RowInput)
现在剩下的就是定义相应的编辑器模板(框架将自动为RowInput集合的每个元素呈现该模板,这样您就不必编写任何循环)。 编辑器模板按惯例工作。 因此,如果您的RowInput
属性是这样定义的:
public IEnumerable<FooBar> RowInput { get; set; }
您定义模板~/Views/Shared/EditorTemplates/FooBar.cshtml
:
@model FooBar
... put your switches and cases and stuff, but I remove this noise to
... make the answer more readable
@Html.DropDownListFor(blah => blah.InputtedData, ddv)
@Html.HiddenFor(blah => blah.InputtedDataID)
@Html.HiddenFor(blah => blah.RowCtrl.CtrlTypeID)
但是由于您的表单包含所有记录,因此要发送的相应控制器操作必须与顶级视图模型一起使用,因为您将发送所有内容:
[HttpPost]
public ActionResult Index(FormRowModel model)
{
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.