如何在MVC视图中访问类的数据属性

时间:2012-01-15 14:09:49

标签: asp.net-mvc asp.net-mvc-3

我有以下课程:

namespace Storage.Models
{
    public class AdminDetail
    {
        public string PartitionKey { get; set; }
        public string RowKey { get; set; }
        public string Title { get; set; }
        public string Status { get; set; }
        public string Type { get; set; }
        public string Level { get; set; }
        [DisplayName("Display Order")]
        public string Order { get; set; }
        public int Row { get; set; }
    }

我有一些建议,我在视图中将以下内容设置为模型:

@model IEnumerable<AdminDetail>

我是否有可能以某种方式引用我的AdminDetail类的属性,例如[DisplayName(“Display Order”)]。我想做的就是显示表格网格第一行的列标签。

<div>@Html.LabelFor(model => Model.Order)</div>

但我不知道如何做到这一点,因为我的模型是集合而不是单个实例。

以下是我用于为视图生成数据的代码:

        IEnumerable<AdminDetail> details = null;
        IList<AdminDetail> detailsList = null;
        details = from t in _table
                      select new AdminDetail
                      {
                          PartitionKey = t.PartitionKey,
                          RowKey = t.RowKey,
                          Title = t.Title,
                          Status = t.Status,
                          Type = t.Type,
                          Level = t.Level,
                          Order = t.Order
                      };
            #endregion
            detailsList = details
                .OrderBy(item => item.Order)
                .ThenBy(item => item.Title)
                .Select((t, index) => new AdminDetail() { 
                    PartitionKey = t.PartitionKey, 
                    RowKey = t.RowKey, 
                    Title = t.Title, 
                    Status = t.Status, 
                    Type = t.Type, 
                    Level = t.Level, 
                    Order = t.Order, 
                    Row = index + 1 })
                 .ToList();

 return detailsList;

2 个答案:

答案 0 :(得分:2)

@model IEnumerable<AdminDetail>

@foreach (var detail in Model)
{
    <div>@Html.LabelFor(x => detail.Order)</div>
}

或者如果您使用的是我推荐的编辑器模板:

@model IEnumerable<AdminDetail>
@Html.EditorForModel()

然后在显示模板(~/Views/Shared/EditorTemplates/AdminDetail.cshtml)内:

@model AdminDetail
<div>@Html.LabelFor(model => model.Order)</div>

更新:

您可以使用IList<AdminDetail>作为您的视图模型类型,它将为您提供元素的索引访问权限,您可以像这样获取元数据:

@model IList<AdminDetail>

<table>
    <thead>
        <tr>
            <th>@Html.LabelFor(x => x[0].Order)</th>
        </tr>
    </thead>
    <tbody>
        @Html.DisplayForModel()
    </tbody>
</table>

并在显示模板(~/Views/Shared/DisplayTemplates/AdminDetail.cshtml)内:

@model AdminDetail
<tr>
    <td>@Html.DisplayFor(x => x.Order)</td>
</tr>

答案 1 :(得分:1)

由于您正在尝试创建一个表,并且只需要一次标签,只需实例化所需类的新项并在其上调用LabelFor方法。

@{ var labelModel = new AdminDetail; }
@Html.LabelFor(model => labelModel.Order);

这有点像一种hacky方式,但它会阻止你编写自己的反射,它不会将标题中的标签绑定到页面上的特定输入。