Reputation: 32758
I have the following class:
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; }
}
I had some advice and I set up the following as the model in my view:
@model IEnumerable<AdminDetail>
Is it possible for me to somehow reference attributes of my AdminDetail class such as [DisplayName("Display Order")]. What I would like to do is something like this to show column labels for the first row of my table grid.
<div>@Html.LabelFor(model => Model.Order)</div>
But I am not sure how to do this as my model is of a collection and not a single instance.
Here's the code I use to generate data for the view:
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;
Upvotes: 1
Views: 528
Reputation: 1038710
@model IEnumerable<AdminDetail>
@foreach (var detail in Model)
{
<div>@Html.LabelFor(x => detail.Order)</div>
}
or if you are using an editor template which is what I would recommend:
@model IEnumerable<AdminDetail>
@Html.EditorForModel()
and then inside the display template (~/Views/Shared/EditorTemplates/AdminDetail.cshtml
):
@model AdminDetail
<div>@Html.LabelFor(model => model.Order)</div>
UPDATE:
You could use IList<AdminDetail>
as your view model type which will give you index access to elements and you could fetch the metadata like this:
@model IList<AdminDetail>
<table>
<thead>
<tr>
<th>@Html.LabelFor(x => x[0].Order)</th>
</tr>
</thead>
<tbody>
@Html.DisplayForModel()
</tbody>
</table>
and inside the display template (~/Views/Shared/DisplayTemplates/AdminDetail.cshtml
):
@model AdminDetail
<tr>
<td>@Html.DisplayFor(x => x.Order)</td>
</tr>
Upvotes: 2
Reputation: 18877
Since you are trying to make a table, and just need the label one time, just instantiate a new item of the class you want and call the LabelFor
methods on it.
@{ var labelModel = new AdminDetail; }
@Html.LabelFor(model => labelModel.Order);
It's a bit of a hacky way to do it, but it will prevent you from writing your own reflection and it won't tie the label in the header to a specific input on the page.
Upvotes: 1