在我的MVC4应用程序中,我有一个管理员部分。在此管理员视图中,我可以看到已注册的所有尚未接受的用户。该视图也是不可数的编辑器。要拥有IEnumerable的编辑器,我在我的视图中添加了IList和for循环:
@model IList<PlusPlatform.Models.UserProfile>
@{
ViewBag.Title = "Manage";
}
<h2>@ViewBag.Title</h2>
@using (Html.BeginForm())
{
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.UserName)
</th>
<th>
@Html.DisplayNameFor(model => model.FirstName)
</th>
<th>
@Html.DisplayNameFor(model => model.LastName)
</th>
<th>
@Html.DisplayNameFor(model => model.DepartmentId)
</th>
<th>
@Html.DisplayNameFor(model => model.IsActivated)
</th>
</tr>
@for (var i = 0; i < Model.Count(); i++) {
<tr>
<td>
@Html.EditorFor(modelItem => Model[i].UserName)
</td>
<td>
@Html.EditorFor(modelItem => Model[i].FirstName)
</td>
<td>
@Html.EditorFor(modelItem => Model[i].LastName)
</td>
<td>
@Html.EditorFor(modelItem => Model[i].DepartmentId)
</td>
<td>
@Html.EditorFor(modelItem => Model[i].IsActivated)
</td>
</tr>
}
</table>
<input type="submit" value="Save" />
}
但现在的问题是我无法使用Html.DisplayNameFor和Html.LabelFor。如何正确显示标签?
答案 0 :(得分:1)
如果您真的不关心IList<T>
,可以将模型更改为IEnumerable<T>
。 DisplayNameFor方法有IEnumerable
的重载,这意味着您可以执行此操作:
@model IEnumerable<PlusPlatform.Models.UserProfile>
...
<th>
@Html.DisplayNameFor(model => model.UserName)
</th>
LabelFor
没有此重载,因为label
应该用于特定元素,例如:
@Html.LabelFor(modelItem => Model[i].UserName)
修改强>
如果您想将该数据发布到控制器,请更好地创建EditorTemplate
,并将其命名为UserProfile
:
@model PlusPlatform.Models.UserProfile
<tr>
<td>
@Html.EditorFor(m=> m.UserName)
</td>
<td>
@Html.EditorFor(m=> m.FirstName)
</td>
<td>
@Html.EditorFor(m=> m.LastName)
</td>
<td>
@Html.EditorFor(m=> m.DepartmentId)
</td>
<td>
@Html.EditorFor(m=> m.IsActivated)
</td>
</tr>
然后在View中摆脱循环:
@model IEnumerable<PlusPlatform.Models.UserProfile>
@using (Html.BeginForm())
{
<table>
<tr>
<th>
@Html.DisplayNameFor(model => model.UserName)
</th>
...
</tr>
@Html.EditorForModel()
</table>
}
答案 1 :(得分:0)
试试这个
@using (Html.BeginForm())
{
<table>
<tr>
<th>
<label@Html.DisplayNameFor(m =>m.First().UserName)</label>
</th>
<th>
<label>@Html.DisplayNameFor(m =>m.First().FirstName)</label>
</th>
<th>
<label>@Html.DisplayNameFor(m =>m.First().LastName)</label>
</th>
<th>
<label>@Html.DisplayNameFor(m =>m.First().DepartmentId)</label>
</th>
<th>
<label>@Html.DisplayNameFor(m =>m.First().IsActivated)</label>
</th>
</tr>
@for (var i = 0; i < Model.Count(); i++) {
<tr>
<td>
@Html.EditorFor(modelItem => Model[i].UserName)
</td>
<td>
@Html.EditorFor(modelItem => Model[i].FirstName)
</td>
<td>
@Html.EditorFor(modelItem => Model[i].LastName)
</td>
<td>
@Html.EditorFor(modelItem => Model[i].DepartmentId)
</td>
<td>
@Html.EditorFor(modelItem => Model[i].IsActivated)
</td>
</tr>
}
答案 2 :(得分:0)
如果你能以这种方式使用EditorFor,那么为什么不使用DisplayFor? 试试这个
@Html.LabelFor(modelItem => Model[0].FirstName)