这段代码
<%= Html.LabelFor(model => model.Name) %>
产生这个
<label for="Name">Name</label>
但是我想要这个
<label for="Name" class="myLabel">Name</label>
你是怎样做的?
Answers:
好的,查看此方法的源代码(System.Web.Mvc.Html.LabelExtensions.cs),似乎没有办法使用ASP.NET MVC 2中的HtmlHelper来做到这一点。是要创建自己的HtmlHelper或对此特定标签执行以下操作:
<label for="Name" class="myLabel"><%= Model.Name %></label>
@Html.Label
于Razor Web Pages中的帮助程序。
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));
}
}