.NET MVC - How to assign a class to Html.LabelFor?

后端 未结 3 373
刺人心
刺人心 2021-01-31 01:08

This code

<%= Html.LabelFor(model => model.Name) %>

produces this


         


        
3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-31 01:59

    Overload of LabelFor:

    public static class NewLabelExtensions
    {
        public static MvcHtmlString LabelFor(this HtmlHelper html, Expression> expression, object htmlAttributes)
        {
            return LabelFor(html, expression, new RouteValueDictionary(htmlAttributes));
        }
        public static MvcHtmlString LabelFor(this HtmlHelper html, Expression> expression, IDictionary 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));
            tag.SetInnerText(labelText);
            return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
        }
    }
    

    http://weblogs.asp.net/imranbaloch/archive/2010/07/03/asp-net-mvc-labelfor-helper-with-htmlattributes.aspx

提交回复
热议问题