.NET MVC – 如何分配一个类到Html.LabelFor?

这个代码

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

产生这个

 <label for="Name">Name</label> 

但是我想要这个

 <label for="Name" class="myLabel">Name</label> 

你是怎样做的?

好的,看这个方法的源代码(System.Web.Mvc.Html.LabelExtensions.cs),似乎没有办法用ASP.NET MVC 2中的HtmlHelper来做到这一点。我认为你最好的select要么创build自己的HtmlHelper,要么为此特定标签执行以下操作:

 <label for="Name" class="myLabel"><%= Model.Name %></label> 

不幸的是,在MVC 3中 ,Html.LabelFor()方法没有允许直接声明类的方法签名。 但是, MVC 4添加了2个接受htmlAttributes匿名对象的重载。

和所有的HtmlHelpers一样,记住C#编译器将class看作保留字是很重要的。

所以如果你在class属性之前使用了@,它可以解决这个问题,例如:

 @Html.LabelFor(model => model.PhysicalPostcode, new { @class= "SmallInput" }) 

@符号使“class”成为一个通过的文字。

LabelFor的重载:

 public static class NewLabelExtensions { 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)); 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