如何在@ html.LabelFor()中指定内容

时间:2014-10-14 13:25:37

标签: c# asp.net-mvc razor

我在剃须刀视图中有以下内容:

   @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })

现在我想在模型名称后附加以下内容:<span class="asterisk">*</span>

所以一旦它呈现它看起来像:

<label class="control-label col-md-2">Name <span class="asterisk">*</span></label>

或者可能是替代。

也许我可以覆盖LabelFor方法以查看该数据模型项是否具有Required元数据标记,如果是,它将自动添加Asterisk。

1 个答案:

答案 0 :(得分:3)

您无法覆盖LabelFor,但您可以添加自己的HtmlHelper扩展方法:

public static MvcHtmlString RequiredIndicatorLabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> modelProperty)
{
   return RequiredIndicatorLabelFor(html, modelProperty, null);
}

public static MvcHtmlString RequiredIndicatorLabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> modelProperty, object htmlAttributes)
{
    var htmlAttributesDict = new RouteValueDictionary(htmlAttributes);
    var metadata = ModelMetadata.FromLambdaExpression(modelProperty, html.ViewData);

    // To just add a class to the label tag
    // if (metadata.IsRequired)
    // {
    //     var cssClass = htmlAttributesDict["class"];
    //     htmlAttributesDict["class"] = (cssClass == null) ? "required" : cssClass + " required";
    // }
    // return html.LabelFor(modelProperty, metadata.GetDisplayName(), htmlAttributesDict);

    // To add text/HTML to content of label tag
    var builder = new TagBuilder("label");
    builder.MergeAttribute("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId());
    builder.MergeAttributes(htmlAttributesDict);
    builder.SetInnerText(metadata.GetDisplayName());

    if (metadata.IsRequired)
    {
        var spanBuilder = new TagBuilder("span");
        spanBuilder.AddCssClass("asterisk");
        spanBuilder.SetInnerText("*");
        builder.InnerHtml += " " + spanBuilder.ToString();
    }
    return new MvcHtmlString(builder.ToString());
}