Html 在 MVC razor 中显示模型的列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21852798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Show a list from a model in MVC razor
提问by Carel
Can I enumerate a list from the model in the razor?
我可以从剃刀中的模型中列举一个列表吗?
My model:
我的型号:
public class PreapprovalViewModel
{
public int ProjectId { get; set; }
public int Decision { get; set; }
public List<BranchHead> BranchHeads { get; set; }
public List<SelectListItem> Decisions { get; set; }
}
On the index for Preapproval I want a table that shows some fields within the BranchHead list.
在 Preapproval 的索引上,我想要一个显示 BranchHead 列表中某些字段的表。
Razor:
剃刀:
@model Mars.Intranet.ViewModels.PreapprovalViewModel
@{
ViewBag.Title = "Index";
}
@Html.Partial("_ProjectPartial")
<h2>Preapproval</h2>
@using (Html.BeginForm()) {
<div>
Approve research request:
@Html.DropDownListFor(o => o.Decision, Model.Decisions)
</div>
<div id="assign-branch-head" style="display: none;">
Assign branch heads
<table>
<tr>
<th>@Html.DisplayFor(o => o.BranchHeads.BranchName</th> <!-- Can I access the list in the model like this?-->
<th>@Html.DisplayFor(o => p.BranchHeads.FirstName</th> <!-- Can I access the list in the model like this?-->
<th>@Html.DisplayFor(o => p.BranchHeads.Comment</th> <!-- Can I access the list in the model like this?-->
</tr>
<tr>
<td><!-- I want the info from the list in model here--></td>
<td><!-- I want the info from the list in model here--></td>
<td><!-- I want the info from the list in model here--></td>
</tr>
</table>
</div>
<div class="approval-comment">
Comment:
@Html.TextAreaFor(o => o.Comment)
</div>
<button type="submit" class="btn_submit"></button>
}
回答by Marco
Yes, this is totally possible. But since this is a List<T>
you need to iterate over it in order to display the data.
是的,这是完全可能的。但由于这是一个,List<T>
您需要对其进行迭代以显示数据。
Just wrap your data in a foreach loop
只需将您的数据包装在 foreach 循环中
@foreach (var item in Model.BranchHeads)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.BranchName)<br/>
</td>
<td>
@Html.DisplayFor(modelItem => item.FirstName)<br/>
</td>
<td>
@Html.DisplayFor(modelItem => item.Comment)<br/>
</td>
</tr>
}
In addition, you might want to use Html.DisplayNameFor()
to display the table headers.
此外,您可能希望使用Html.DisplayNameFor()
来显示表格标题。