我正在尝试使用数组来遍历模型字段
@Html.DisplayNameFor(model => model.[fld])
其中fld在数组中
flds见下面的代码。请让我知道如何做到这一点。
@model IEnumerable<SchoolAutomationSite.Models.tblClass>
@{
ViewBag.Title = "List Of Classes";
}
<h2>@ViewBag.Title</h2>
<p>
@Html.ActionLink("Create New Class", "Create")
</p>
<table class="table">
<tr>
这是数组
@{
string[] DisplayName = { "name", "description", "createdAt", "updatedAt" };
}
@foreach (var fld in flds)
{
<th>
@Html.DisplayNameFor(model => model.[fld])
如何做上述内容?
</th>
}
</tr>
@foreach (var item in Model) {
<tr>
@foreach (var fld in flds)
{
<td>
@Html.DisplayFor(modelItem => item.[flds])
</td>
}
use the above instead off
----------
<td>
@Html.DisplayFor(modelItem => item.name)
</td>
<td>
@Html.DisplayFor(modelItem => item.description)
</td>
<td>
@Html.DisplayFor(modelItem => item.createdAt)
</td>
<td>
@Html.DisplayFor(modelItem => item.updatedAt)
</td>
----------
</tr>
}
</table>
答案 0 :(得分:0)
您可以将dotNet对象转换为字典,然后遍历密钥集合。这是我过去使用过的扩展方法:
public static class ObjectExtensions
{
/// <summary>
/// Turns object into dictionary
/// </summary>
/// <param name="o"></param>
/// <returns></returns>
public static IDictionary<string, TVal> ToDictionary<TVal>(this object o)
{
if (o != null)
{
var props = TypeDescriptor.GetProperties(o);
var d = new Dictionary<string, TVal>();
foreach (var prop in props.Cast<PropertyDescriptor>())
{
var val = prop.GetValue(o);
if (val != null)
{
d.Add(prop.Name, (TVal)val);
}
}
return d;
}
return new Dictionary<string, TVal>();
}
}
然后像这样称呼它:
var fields = Model.ToDictionary();
foreach (var key in fields.Keys) {
<td>
@fields[key]
</td>
}
或者,使用你的flds数组:
var fields = Model.ToDictionary();
foreach (var fld in flds) {
<td>
@fields[fld]
</td>
}