如何覆盖@ Html.LabelFor模板?


70

我有一个简单的字段表格

<div class="field fade-label">
    @Html.LabelFor(model => model.Register.UserName)
    @Html.TextBoxFor(model => model.Register.UserName)
</div>

结果是:

<div class="field fade-label">
    <label for="Register_UserName">Username (used to identify all services, from 4 to 30 chars)</label>
    <input type="text" value="" name="Register.UserName" id="Register_UserName">
</div>

但我希望该LabelFor代码在<span>内部附加一个,这样我最终可以拥有:

<label for="Register_UserName">
    <span>Username (used to identify all services, from 4 to 30 chars)</span>
</label>

我怎样才能做到这一点?

所有示例都使用,EditorTemplates但这是一个LabelFor


由于签名与现有扩展方法相同,因此将导致歧义的调用异常。没有最重要的扩展方法。
Nilzor 2011年

@Nilzor,没有此类参数的扩展名,您可以安全地在我的答案中使用代码,请记住,LabelFor不是EditorFor
balexandre

你是对的。我应该说的是,您的方法不会覆盖@ Html.LabelFor(model => model.Register.UserName)构造。如果您尝试使用此签名添加重载,则您将得到一个模棱两可的调用异常,正如我测试过的那样。您的解决方案是合理的,但是需要您更改调用代码(视图)。
Nilzor

@balexandre如何覆盖“普通” LabelFor方法?
罗米亚斯

请将您编辑过的解决方案移到下面的实际答案中。
BoltClock

Answers:


72

您可以通过创建自己的HTML帮助器来做到这一点。

http://www.asp.net/mvc/tutorials/creating-custom-html-helpers-cs

您可以通过下载ASP.Net MVC的源并将其修改为自定义帮助器来查看LabelFor <>的代码。


答案balexandre添加

public static class LabelExtensions
{
    public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object htmlAttributes)
    {
        return LabelFor(html, expression, new RouteValueDictionary(htmlAttributes));
    }
    public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, IDictionary<string, object> htmlAttributes)
    {
        ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
        string htmlFieldName = ExpressionHelper.GetExpressionText(expression);
        string labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
        if (String.IsNullOrEmpty(labelText))
        {
            return MvcHtmlString.Empty;
        }

        TagBuilder tag = new TagBuilder("label");
        tag.MergeAttributes(htmlAttributes);
        tag.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));

        TagBuilder span = new TagBuilder("span");
        span.SetInnerText(labelText);

        // assign <span> to <label> inner html
        tag.InnerHtml = span.ToString(TagRenderMode.Normal);

        return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
    }
}

2
知道了,将最终代码添加到我的问题中,任何人都可以复制/粘贴/使用。感谢您的注意。
balexandre

我以这种扩展方法作为开始,但是由于它没有使用参数fieldName覆盖LabelFor方法,因此我对其进行了一些更新。
reaper_unique 2014年

5
使用此方法时如何解决歧义调用错误。现在有两种LabelFor方法,一种来自默认MVC,另一种是。
Ruchan 2014年

@Ruchan你有没有解决这个问题?
HaBo

必须用其他名称重命名我自己的帮助器。
Ruchan

5

我扩展了balealexandre的答案,并添加了指定HTML的功能,以在标签文本之前和之后都包含HTML。我添加了一堆方法重载和注释。希望对大家有帮助!

还从此处获取信息: 使用HTML帮助器在标签内部的HTML

namespace System.Web.Mvc.Html
{
    public static class LabelExtensions
    {
        /// <summary>Creates a Label with custom Html before the label text.  Only starting Html is provided.</summary>
        /// <param name="startHtml">Html to preempt the label text.</param>
        /// <returns>MVC Html for the Label</returns>
        public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, Func<object, HelperResult> startHtml)
        {
            return LabelFor(html, expression, startHtml, null, new RouteValueDictionary("new {}"));
        }

        /// <summary>Creates a Label with custom Html before the label text.  Starting Html and a single Html attribute is provided.</summary>
        /// <param name="startHtml">Html to preempt the label text.</param>
        /// <param name="htmlAttributes">A single Html attribute to include.</param>
        /// <returns>MVC Html for the Label</returns>
        public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, Func<object, HelperResult> startHtml, object htmlAttributes)
        {
            return LabelFor(html, expression, startHtml, null, new RouteValueDictionary(htmlAttributes));
        }

        /// <summary>Creates a Label with custom Html before the label text.  Starting Html and a collection of Html attributes are provided.</summary>
        /// <param name="startHtml">Html to preempt the label text.</param>
        /// <param name="htmlAttributes">A collection of Html attributes to include.</param>
        /// <returns>MVC Html for the Label</returns>
        public static MvcHtmlString LabelFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression, Func<object, HelperResult> startHtml, IDictionary<string, object> htmlAttributes)
        {
            return LabelFor(html, expression, startHtml, null, htmlAttributes);
        }

        /// <summary>Creates a Label with custom Html before and after the label text.  Starting Html and ending Html are provided.</summary>
        /// <param name="startHtml">Html to preempt the label text.</param>
        /// <param name="endHtml">Html to follow the label text.</param>
        /// <returns>MVC Html for the Label</returns>
        public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, Func<object, HelperResult> startHtml, Func<object, HelperResult> endHtml)
        {
            return LabelFor(html, expression, startHtml, endHtml, new RouteValueDictionary("new {}"));
        }

        /// <summary>Creates a Label with custom Html before and after the label text.  Starting Html, ending Html, and a single Html attribute are provided.</summary>
        /// <param name="startHtml">Html to preempt the label text.</param>
        /// <param name="endHtml">Html to follow the label text.</param>
        /// <param name="htmlAttributes">A single Html attribute to include.</param>
        /// <returns>MVC Html for the Label</returns>
        public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, Func<object, HelperResult> startHtml, Func<object, HelperResult> endHtml, object htmlAttributes)
        {
            return LabelFor(html, expression, startHtml, endHtml, new RouteValueDictionary(htmlAttributes));
        }

        /// <summary>Creates a Label with custom Html before and after the label text.  Starting Html, ending Html, and a collection of Html attributes are provided.</summary>
        /// <param name="startHtml">Html to preempt the label text.</param>
        /// <param name="endHtml">Html to follow the label text.</param>
        /// <param name="htmlAttributes">A collection of Html attributes to include.</param>
        /// <returns>MVC Html for the Label</returns>
        public static MvcHtmlString LabelFor<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> expression, Func<object, HelperResult> startHtml, Func<object, HelperResult> endHtml, IDictionary<string, object> htmlAttributes)
        {
            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
            string htmlFieldName = ExpressionHelper.GetExpressionText(expression);

            //Use the DisplayName or PropertyName for the metadata if available.  Otherwise default to the htmlFieldName provided by the user.
            string labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
            if (String.IsNullOrEmpty(labelText))
            {
                return MvcHtmlString.Empty;
            }

            //Create the new label.
            TagBuilder tag = new TagBuilder("label");

            //Add the specified Html attributes
            tag.MergeAttributes(htmlAttributes);

            //Specify what property the label is tied to.
            tag.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));

            //Run through the various iterations of null starting or ending Html text.
            if (startHtml == null && endHtml == null) tag.InnerHtml = labelText;
            else if (startHtml != null && endHtml == null) tag.InnerHtml = string.Format("{0}{1}", startHtml(null).ToHtmlString(), labelText);
            else if (startHtml == null && endHtml != null) tag.InnerHtml = string.Format("{0}{1}", labelText, endHtml(null).ToHtmlString());
            else tag.InnerHtml = string.Format("{0}{1}{2}", startHtml(null).ToHtmlString(), labelText, endHtml(null).ToHtmlString());

            return MvcHtmlString.Create(tag.ToString());
        }
    }
}

3

LabelFor是扩展方法(静态),因此不能被覆盖。您需要创建自己的Html Helper Extension方法才能实现所需的功能。


2
尽管编辑器模板的TOO是静态方法,但它们可以被“覆盖”。
林哥伦2011年

1
我们这里不讨论编辑器模板。编辑器模板是通过约定发现的局部视图。它与扩展方法的替代或静态声明无关。
达伦·刘易斯

12
是的,但是当有人看到LabelFor,然后看到它与EditorFor相似时,他可能会认为也可以按惯例覆盖它。这正是OP要求的。这与方法重载和静态方法无关。
林哥伦2011年
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.