[英]How do I Bind a Collection (IEnumerable) of a custom type?
我有以下操作来显示一个包含 3 个项目的表单:
[HttpGet]
public ActionResult ReferAFriend()
{
List<ReferAFriendModel> friends = new List<ReferAFriendModel>();
ReferAFriendModel f1 = new ReferAFriendModel();
ReferAFriendModel f2 = new ReferAFriendModel();
ReferAFriendModel f3 = new ReferAFriendModel();
friends.Add(f1);
friends.Add(f2);
friends.Add(f3);
return View(friends);
}
然后是 Post 动作
[HttpPost]
public ActionResult ReferAFriend(IEnumerable<ReferAFriendModel> friends)
{
if(ModelState.IsValid){
编辑我的视图如下所示:
@model IEnumerable<Models.ReferAFriendModel>
@for(int i=0;i<Model.Count();i++)
{
@Html.Partial("_ReferAFriend", Model.ElementAt(i));
}
部分看起来像这样:
@model Models.ReferAFriendModel
<p>
@Html.LabelFor(i => i.FullName) @Html.TextBoxFor(i => i.FullName)<br />
@Html.LabelFor(i => i.EmailAddress) @Html.TextBoxFor(i => i.EmailAddress)
@Html.HiddenFor(i=>i.Id)
</p>
当我发布时,我可以看到这些字段发布在 Request.Form object 例如 Request.Form["FullName"] 将显示:"David Beckham","Thierry Henry"。 “Chicharito Fergurson”,这是我在表格中输入的值。 但是,在 Post 操作中,“friends”的值始终是 null。 ReferAFriendModel 具有三个公共属性 Id、EmailAddress 和 FullName。
我究竟做错了什么?
您可以查看以下有关 arrays 和字典的电汇格式的博客文章。 就个人而言,我总是在我的视图中使用编辑器模板,这些模板负责生成输入字段的正确名称,以便默认的 model 绑定器能够正确绑定值。
@model IEnumerable<ReferAFriendModel>
@using (Html.BEginForm())
{
@Html.EditorForModel()
<input type="submit" value="OK" />
}
并在相应的编辑器模板( ~/Views/Shared/EditorTemplates/ReferAFriendModel.cshtml
)中:
@model ReferAFriendModel
@Html.EditorFor(x => x.Prop1)
@Html.EditorFor(x => x.Prop2)
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.