问题描述
|
问题:
提交表单时,我丢失了输入到地址的编辑模板中的所有信息。
我有以下模型:
public class MoveRecord
{
public Address StartPoint { get; set; }
public Address EndPoint { get; set; }
}
其中“地址”定义为:
public class Address
{
public String City { get; set;}
public String State { get; set; }
public String Line1{ get; set; }
public String PostalCode { get; set; }
}
这是我的操作方法:
[HttpPost]
public ActionResult Edit(MoveRecord model)
{
if (ModelState.IsValid)
{
//Save info
}
return View(model);
}
我的编辑视图使用:
using (Html.BeginForm(\"Edit\",\"Move\",FormMethod.Post))
{
@Html.EditorFor(m => m.StartPoint);
@Html.EditorFor(m => m.EndPoint);
<input type=\"submit\" value=\"Save\" />
}
我的编辑模板是:
<table class=\"form address\">
<tbody>
<tr>
<th style=\"width: 200px;\">
@Html.LabelFor(m => m.Line1):
</th>
<td>
@Html.TextBoxFor(m => m.Line1,new { style = \"width: 300px;\" })
</td>
</tr>
<tr id=\"zip\">
<th>
@Html.LabelFor(m => m.PostalCode):
</th>
<td>
@Html.TextBoxFor(m => m.PostalCode,new { style = \"width: 150px;\" })
</td>
</tr>
<tr id=\"city\">
<th>
@Html.LabelFor(m => m.City):
</th>
<td>
@Html.TextBoxFor(m => m.City,new { style = \"width: 150px;\" })
</td>
</tr>
<tr id=\"state\">
<th>
@Html.LabelFor(m => m.StateProvince):
</th>
<td>
@Html.TextBoxFor(m => m.StateProvince,new { style = \"width: 150px;\" })
</td>
</tr>
</tbody>
</table>
一切都很好,但是当我提交表单时,在action方法中获得的模型不包含任何输入到地址字段中的信息。如果我将所有内容都移到同一视图中,则可以正常工作,但我希望能够使用编辑器模板使视图易于阅读。如何从正确绑定到模型的编辑器模板中获取数据?
编辑:发布了我的操作方法
解决方法
您提交表单的操作必须如下所示:
[HttpPost]
public ActionResult Edit(MoveRecord model)
{
// model.StartPoint and model.EndPoint should be correctly bound here.
...
}
或者,如果您尝试直接绑定到这两个地址,则需要设置正确的前缀:
[HttpPost]
public ActionResult Edit(
[Bind(Prefix = \"StartPoint\")] Address start,[Bind(Prefix = \"EndPoint\")] Address end
)
{
...
}