Asp.Net MVC 2 LabelFor Custom Text

后端 未结 4 2033
南旧
南旧 2021-01-01 17:39

Is there a way to use the LabelFor helper and customize the label text without having to use the DisplayNameAttribute in my model?

4条回答
  •  粉色の甜心
    2021-01-01 18:31

    I have created this html helpers for my project:

    public static class MyLabelExtensions
    {
        public static MvcHtmlString Label(this HtmlHelper htmlHelper, string forName, string labelText)
        {
            return Label(htmlHelper, forName, labelText, (object) null);
        }
    
        public static MvcHtmlString Label(this HtmlHelper htmlHelper, string forName, string labelText,
                                          object htmlAttributes)
        {
            return Label(htmlHelper, forName, labelText, new RouteValueDictionary(htmlAttributes));
        }
        public static MvcHtmlString Label(this HtmlHelper htmlHelper, string forName, string labelText,
                                          IDictionary htmlAttributes)
        {
            var tagBuilder = new TagBuilder("label");
            tagBuilder.MergeAttributes(htmlAttributes);
            tagBuilder.MergeAttribute("for", forName.Replace(".", tagBuilder.IdAttributeDotReplacement), true);
            tagBuilder.SetInnerText(labelText);
            return MvcHtmlString.Create(tagBuilder.ToString(TagRenderMode.Normal));
        }
    
        public static MvcHtmlString LabelFor(this HtmlHelper htmlHelper,
                                                                Expression> expression,
                                                                string labelText)
        {
            return LabelFor(htmlHelper, expression, labelText, (object) null);
        }
        public static MvcHtmlString LabelFor(this HtmlHelper htmlHelper,
                                                                Expression> expression,
                                                                string labelText, object htmlAttributes)
        {
            return LabelFor(htmlHelper, expression, labelText, new RouteValueDictionary(htmlAttributes));
        }
        public static MvcHtmlString LabelFor(this HtmlHelper htmlHelper,
                                                                Expression> expression,
                                                                string labelText,
                                                                IDictionary htmlAttributes)
        {
            string inputName = ExpressionHelper.GetExpressionText(expression);
            return htmlHelper.Label(inputName, labelText, htmlAttributes);
        }
    }
    

    I use them with "strongly typed" resources:

    <%= Html.LabelFor(m=>m.NickName, UserStrings.NickName) %>
    

    Hope that helps...

提交回复
热议问题