1

I'm creating a Asp.net MVC Site for the first type.

I'm creating a Details page, and used something like this:

<ul>
    <li>
        @Html.DisplayNameFor(m => m.MyProp)
        @Html.DisplayFor(m => m.MyProp)
    </li>
<ul>

And I get something like that:

<ul>
    <li>
        MyProp
        MyPropValue
    </li>
<ul>

I'd like my field header and my field value to be wrapped inside individual Span's, so i can format it in a global css, like that:

<ul>
    <li>
        <span class="field-label">MyProp</span>
        <span class="field-value">MyPropValue</span>
    </li>
<ul>

I'd like to find a way to do that without having to enclose every field in a span. I get to solve that for DisplayFor method using a DisplayTemplate, but know i need to do that for DisplayNameFor, in a way that every time i use this Method it generates the span automatically.

I thought about creating my own substitute method for @Html.DisplayNameFor, but I'm a little confused about what would be the signature for that method.

Anybody got any tip on how to achieve that?


Edit: I tried creating a HtmlHelper extension method, like bellow:

public static IHtmlString OxDisplayNameFor<TModel, TField> (this HtmlHelper<TModel> helper, Expression<Func<TModel, TField>> expression)
{
    return new HtmlString(String.Format(
        "<span class='display-label'>{0}</span>", "XXX"));
}

The only thing that remains is: How do i get the value from the expression parameter?

Marlon
  • 1,719
  • 3
  • 20
  • 42

1 Answers1

2

The signature would be the same as for Html.DisplayNameFor:

public static MvcHtmlString DisplayWithDisplayNameFor<TModel, TValue>(
    this HtmlHelper<TModel> html,
    Expression<Func<TModel, TValue>> expression)
{
    // construct a span tag and put html.DisplayNameFor(expression) in it
    // then another span tag and put html.DisplayFor(expression) in it
    // return all that
}

It would be more convenient to have it as a @helper, but you cannot have a generic helper and so cannot pass the property-pointing lambdas to it, so the closest you can do is something like:

@helper DisplayWithDisplayName(MvcHtmlString DisplayName, MvcHtmlString DisplayValue)
{
    <span class="field-label">@DisplayName</span>
    <span class="field-value">@DisplayValue</span>
}

which you would then call as

@DisplayWithDisplayNameFor(Html.DisplayNameFor(m => m.MyProp), Html.DisplayFor(m => m.MyProp))
Community
  • 1
  • 1
GSerg
  • 76,472
  • 17
  • 159
  • 346
  • thanks. The method content was: return new HtmlString(String.Format("{0}", helper.DisplayNameFor(expression).ToString())); Is it the best way? – Marlon Jan 05 '17 at 17:35
  • @Marlon No, I would use `TagBuilder` (e.g. http://stackoverflow.com/q/18214347/11683). – GSerg Jan 05 '17 at 17:45