ASP.. NET MVC c# -使用数组值循环遍历模型字段,例如model.(数组值)

本文关键字:数组 字段 模型 例如 model 遍历 循环 ASP NET MVC | 更新日期: 2023-09-27 18:14:42

我试图使用数组循环通过模型字段@Html.DisplayNameFor(model => model.[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>

ASP.. NET MVC c# -使用数组值循环遍历模型字段,例如model.(数组值)

可以将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>
}