在Asp.net MVC中为DisplayNameFor方法创建模板 [英] Create a Template for DisplayNameFor method in Asp.net MVC

查看:107
本文介绍了在Asp.net MVC中为DisplayNameFor方法创建模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为第一种类型创建一个Asp.net MVC网站.

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>

我得到类似的东西:

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

我希望将字段标题和字段值包装在各个Span中,以便可以在全局CSS中对其进行格式化,如下所示:

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>

我想找到一种方法,而不必将范围中的每个字段都括起来.我可以使用DisplayTemplate解决DisplayFor方法的问题,但是知道我需要针对DisplayNameFor做到这一点,因为我每次使用此Method都会自动生成跨度.

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.

我曾考虑为@ Html.DisplayNameFor创建自己的替代方法,但对于该方法的签名感到有些困惑.

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?

我尝试创建一个HtmlHelper扩展方法,例如下面所示:

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"));
}

唯一剩下的就是:如何从expression参数中获取值?

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

推荐答案

签名与将其作为@helper会更方便,但是您不能拥有通用帮助程序,因此无法将指向属性的lambda传递给它,因此您可以执行的最接近的操作是:

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>
}

您将其称为

@DisplayWithDisplayNameFor(Html.DisplayNameFor(m => m.MyProp), Html.DisplayFor(m => m.MyProp))

这篇关于在Asp.net MVC中为DisplayNameFor方法创建模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆