Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

asp.net mvc 3 - How to extend MVC3 Label and LabelFor HTML helpers?

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

Is there an easy way of extending Label/LabelFor without resorting to copying and extending the ILSpy disasm output of those methods?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...