asp.net-mvc .NET MVC - 如何为 Html.LabelFor 分配一个类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2294250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
.NET MVC - How to assign a class to Html.LabelFor?
提问by Aximili
This code
这段代码
<%= Html.LabelFor(model => model.Name) %>
produces this
产生这个
<label for="Name">Name</label>
But I want this
但我想要这个
<label for="Name" class="myLabel">Name</label>
How do you do that?
你是怎样做的?
采纳答案by Richard Nienaber
Okay, looking at the source (System.Web.Mvc.Html.LabelExtensions.cs) for this method, there doesn't seem to be a way to do this with an HtmlHelper in ASP.NET MVC 2. I think your best bet is to either create your own HtmlHelper or do the following for this specific label:
好的,查看此方法的源代码 (System.Web.Mvc.Html.LabelExtensions.cs),似乎没有办法使用 ASP.NET MVC 2 中的 HtmlHelper 来执行此操作。我认为您最好的选择是创建您自己的 HtmlHelper 或为此特定标签执行以下操作:
<label for="Name" class="myLabel"><%= Model.Name %></label>
回答by Chris and Kasun
Sadly, in MVC 3the Html.LabelFor() method has no method signatures that permit a direct class declaration. However, MVC 4adds 2 overloads that accept an htmlAttributes anonymous object.
遗憾的是,在MVC 3 中,Html.LabelFor() 方法没有允许直接类声明的方法签名。但是,MVC 4添加了 2 个接受 htmlAttributes 匿名对象的重载。
As with all HtmlHelpers it's important to remember that the C# compiler sees classas reserved word.
与所有 HtmlHelpers 一样,重要的是要记住 C# 编译器将其class视为保留字。
So if you use the @ before the class attribute it works around the problem, ie:
因此,如果您在 class 属性之前使用 @ 它可以解决该问题,即:
@Html.LabelFor(model => model.PhysicalPostcode, new { @class= "SmallInput" })
The @ symbol makes the "class" a literal that is passed through.
@ 符号使“类”成为传递的文字。
回答by Vladimir Shmidt
Overload of LabelFor:
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));
}
}

