Mr. Smith
Mr. Smith

Reputation: 4516

Html.LabelFor with Type and a property name?

Is there way to write something like:

@Html.LabelFor(typeof(StackViewModel), "SomeProperty")

I'm generating a table (but can't use @Html.TableFor) and want to use @Html.LabelFor to generate the table column titles, but since the table may or may not have any rows, I don't have an object to work with, just the type of that object.

Edit: Just to clarify, I'm looking to use the typeof() because my situation is like this:

@Html.LabelFor(Model.TableRows.First().Id)

And if "TableRows" has no rows, .First() throws.

Upvotes: 2

Views: 542

Answers (2)

Reza Aghaei
Reza Aghaei

Reputation: 125342

If you want to use a non-generic Html helper and pass a Type and property name, as an option you can create such extension method:

public static MvcHtmlString DisplayNameFor(this HtmlHelper html, 
                                           Type modelType, string expression)
{
    var metadata = ModelMetadataProviders.Current
                      .GetMetadataForProperty(null, modelType, expression);
    return MvcHtmlString.Create(metadata.GetDisplayName());
}

Then you can use it this way:

@Html.DisplayNameFor(typeof(Sample.Models.Category), "Id")

Note:

  • You can enhance the method and add some validation rules and exception handling if you need.
  • For cases that your model is of type IEnumerable<T> and you can use a lambda expression for your property like x=>x.Id you can use @Html.DisplayNameFor(x=>x.Id). It also works if the Model is null or has no rows.

Upvotes: 2

SᴇM
SᴇM

Reputation: 7213

@if(Model != null)
{
    <table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Id)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.FirstName)
        </th>
        <th>
            @Html.DisplayNameFor(model => model.LastName)
        </th> 
    </tr>

    @foreach (var item in Model)
    {
        <tr>
            <td>
                @Html.DisplayFor(modelitem => item.Id)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.FirstName)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.LastName)
            </td>
        </tr>
    }
</table>
}

Or you can replace @Html.DisplayNameFor to @Html.LabelFor.

Why not?

Upvotes: 1

Related Questions