如何扩展 MVC3 Label 和 LabelFor HTML helpers? [英] How to extend MVC3 Label and LabelFor HTML helpers?

查看:15
本文介绍了如何扩展 MVC3 Label 和 LabelFor HTML helpers?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Html.LabelHtml.LabelFor 辅助方法不像大多数其他辅助方法那样支持 htmlAttributes 参数.但是,我想设置 class.像这样:

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" })

是否有一种简单的方法来扩展 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));
}

更新要使用刚刚在项目中创建的扩展方法,请在 Viewsweb.config

Update To use the extension method just created in your project, add this line in your Viewsweb.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 Label 和 LabelFor HTML helpers?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆