如何在ASP.NET MVC2中为
Html.LabelFor()添加“id”属性?
这是我的标签代码:
<%=Html.LabelFor(x => x.FirstName)%>
这是我失败的尝试:
<%=Html.LabelFor(x => x.FirstName,new { @id = "first-name" } )%>
谢谢.
解决方法
这是一个应该做你需要的帮手:
public static MvcHtmlString LabelFor<TModel,TValue>(this HtmlHelper<TModel> html,Expression<Func<TModel,TValue>> expression,string id)
{
ModelMetadata meta = ModelMetadata.FromLambdaExpression(expression,html.ViewData),string 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.Attributes.Add("for",html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));
tag.MergeAttribute("id",id);
tag.SetInnerText(labelText);
return tag.ToMvcHtmlString(TagRenderMode.Normal);
}
来自asp.net mvc源代码中LabelFor帮助器的简单修改.
