asp.net-mvc-3 - 如何扩展 MVC3 Label 和 LabelFor HTML helpers?

标签 asp.net-mvc-3 extension-methods

Html.LabelHtml.LabelFor辅助方法不像大多数其他辅助方法那样支持 htmlAttributes 参数。我想设置class然而。像这样的东西:

Html.LabelFor(model => model.Name, new { @class = "control-label" })

是否有一种简单的方法来扩展 Label/LabelFor 没有 诉诸于复制和扩展这些方法的 ILSpy disasm 输出?

最佳答案

您可以通过创建自己的 LabelFor 轻松扩展标签:

像这样的事情应该做你需要的

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

更新
要使用刚刚在您的项目中创建的扩展方法,请在您的 Views\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>

关于asp.net-mvc-3 - 如何扩展 MVC3 Label 和 LabelFor HTML helpers?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9885548/

相关文章:

c# - 选择 IEnumerable<T> 的下 N 个元素

c# - 使 LINQ 扩展方法应用于我的类

C# 线程安全扩展方法

asp.net-mvc - MVC3 分页,每页项目数

c# - Razor - 在 foreach 循环中设置复选框的 ID

asp.net-mvc-3 - 在 razor html 帮助器中传递数据图标属性

asp.net-mvc-3 - MVC3 SSL 问题 - 当不需要 SSL 时无法从 HTTPS 切换到 HTTP

c# - 泛型类的扩展方法

c# - 具有应用程序名称 IsInRole 的自定义 IPrincipal

c# - 使用扩展方法的 Entity Framework 分页很慢?