如何在@html.LabelFor()中指定内容
本文关键字:@html LabelFor | 更新日期: 2023-09-27 18:26:24
我在剃刀视图中有以下内容:
@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。
您不能覆盖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());
}