Is it possible to use LabelFor for header row in Index view

拜拜、爱过 提交于 2019-11-30 05:32:28

问题


I am trying to leverage DataAnnotation values in ASP.NET MVC Index view. Interesting, code generator uses field names (eg., BlogPost) as opposed to Html.LabelFor(m => Model.ColumNames["BlogPost"]) or something similar (I made it up).

Does it mean, that if the Model is IEnumerable (as in Index view), then it is not possible to get to the Display Name that is specified by DataAnnotation? Hard to believe...

My code is currently a mix of MVC 2 and MVC 3, if it makes any difference.


回答1:


You should, at the very least, be able to get what you want by using a partial view (ascx for WebForms) or a Display/Editor template. In your index page you can loop over your enumerable and pass the item into either a partial view or a template.

There may be a way to do it without having do as I've suggested (and I would be interested in seeing the answer), but what I've suggested should work fine.

EDIT:

After some clarification, here is my updated answer.

You can still get the label for a property while still respecting the DisplayAttribute in data annotations. I tried this real quick and it seems to work fine.

In my view I have the following:

Html.LabelFor(m => m.BlogPosts.First().BlogPostTitle)

This worked even if there were no items in the enumeration itself. When I first tested this I got the property name, then I added decorated the property with the DisplayAttribute and the value of the name property was displayed instead of the standard property name.




回答2:


In MVC 4, the HtmlHelper extensions in the DisplayNameExtensions class allows the following (this is the default scaffolding of a list with column headings)

@model IEnumerable<Entity.Foo>

<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Bar)
        </th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Bar)
        </td>
...

This is because DisplayNameFor has overloads for both TModel and IEnumerable<TModel>:

    public static MvcHtmlString DisplayNameFor<TModel, TValue>
                       (this HtmlHelper<IEnumerable<TModel>> html, 
                        Expression<Func<TModel, TValue>> expression);
    public static MvcHtmlString DisplayNameFor<TModel, TValue>
                       (this HtmlHelper<TModel> html, 
                        Expression<Func<TModel, TValue>> expression);


来源:https://stackoverflow.com/questions/4709367/is-it-possible-to-use-labelfor-for-header-row-in-index-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!