如何延长MVC3标签和LabelFor HTML佣工? [英] How to extend MVC3 Label and LabelFor HTML helpers?
本文介绍了如何延长MVC3标签和LabelFor HTML佣工?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Html.Label
和 Html.LabelFor
helper方法不支持htmlAttributes参数像大多数其他佣工做。我想设置类
但是。事情是这样的:
Html.Label
and Html.LabelFor
helper methods do not support the htmlAttributes parameter like most of the other helpers do. I would like to set the class
however. Something like this:
Html.LabelFor(model => model.Name, new { @class = "control-label" })
是否有一个的延长容易的办法标签/ LabelFor的没有诉诸复制和扩大这些方法的ILSpy DISASM输出?
Is there an easy way of extending Label/LabelFor without resorting to copying and extending the ILSpy disasm output of those methods?
推荐答案
您可以轻松地创建自己的LabelFor扩展标签:
You can easily extend the label by creating your own LabelFor:
这样的事情应该做您的需要。
Something like this should do what you need
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));
}
更新
在使用时只需在你的项目中创建的扩展方法,在加入这一行的视图\\ web.config中
<pages>
<namespaces>
<add namespace="System.Web.Helpers" />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Web.WebPages" />
<add namespace="MyProject.Helpers" /> <-- my extension
...
</namespaces>
</pages>
这篇关于如何延长MVC3标签和LabelFor HTML佣工?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文