如何修改LabelFor在必填字段上显示星号?

我想为HtmlHelper创build一个扩展方法,它允许我创build一个LabelFor属性,在它后面显示一个星号(如果它是必填字段)。 我怎样才能做到这一点?

 public class Foo { [Required] public string Name { get; set; } } Html.LabelFor(o => o.Name) // Name* 

这是一篇博客文章 ,介绍如何做到这一点。

给你一个从上面的网站修改的小例子(注意 – 我没有编译/testing过):

 namespace HelpRequest.Controllers.Helpers { public static class LabelExtensions { public static MvcHtmlString Label(this HtmlHelper html, string expression, string id = "", bool generatedId = false) { return LabelHelper(html, ModelMetadata.FromStringExpression(expression, html.ViewData), expression, id, generatedId); } [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string id = "", bool generatedId = false) { return LabelHelper(html, ModelMetadata.FromLambdaExpression(expression, html.ViewData), ExpressionHelper.GetExpressionText(expression), id, generatedId); } internal static MvcHtmlString LabelHelper(HtmlHelper html, ModelMetadata metadata, string htmlFieldName, string id, bool generatedId) { string labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last(); if (String.IsNullOrEmpty(labelText)) { return MvcHtmlString.Empty; } var sb = new StringBuilder(); sb.Append(labelText); if (metadata.IsRequired) sb.Append("*"); var tag = new TagBuilder("label"); if (!string.IsNullOrWhiteSpace(id)) { tag.Attributes.Add("id", id); } else if (generatedId) { tag.Attributes.Add("id", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName) + "_Label"); } tag.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName)); tag.SetInnerText(sb.ToString()); return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal)); } } } 

您可以纯粹通过CSS将星号添加到必填字段。

首先,为它创build一个CSS类:

 .required:after { content: "*"; font-weight: bold; color: red; } 

这将附加一个红色的星号到任何具有“required”类的元素。

然后,在您看来,只需将新类添加到您的标签:

  @Html.LabelFor(m => m.Name, new { @class="required" }) 

更好的可能是一个自定义的HTML Helper,如果该字段有一个[Required]属性,则判断该属性,如果是,则添加“required”CSS类。

我这样做是因为我的必填字段必须是dynamic的(在configuration文件中定义)

在视图的末尾添加:

  <script type="text/javascript"> $('input[type=text]').each(function () { var req = $(this).attr('data-val-required'); if (undefined != req) { var label = $('label[for="' + $(this).attr('id') + '"]'); var text = label.text(); if (text.length > 0) { label.append('<span style="color:red"> *</span>'); } } }); </script> 

这里是我的解决scheme,基于Adam Tuliper的答案,但被修改为使用Bootstrap ,并允许使用自定义属性

 using System; using System.Linq; using System.Web.Mvc; using System.Linq.Expressions; using System.ComponentModel; public static class RequiredLabel { public static MvcHtmlString RequiredLabelFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, object htmlAttributes) { var metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData); string htmlFieldName = ExpressionHelper.GetExpressionText(expression); string labelText = metaData.DisplayName ?? metaData.PropertyName ?? htmlFieldName.Split('.').Last(); if (metaData.IsRequired) labelText += "<span class=\"required\">*</span>"; if (String.IsNullOrEmpty(labelText)) return MvcHtmlString.Empty; var label = new TagBuilder("label"); label.Attributes.Add("for", helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName)); foreach (PropertyDescriptor prop in TypeDescriptor.GetProperties(htmlAttributes)) { label.MergeAttribute(prop.Name.Replace('_', '-'), prop.GetValue(htmlAttributes).ToString(), true); } label.InnerHtml = labelText; return MvcHtmlString.Create(label.ToString()); } } 

然后,我从这个angular度来看它:

 @Html.RequiredLabelFor(model => model.Category, new { @class = "control-label col-md-3" }) 

PS请确保您不要忘记在您的视图中包含您的名称空间。

在这里看到这个post – 应该包含你所需要的大部分http://blogs.planetcloud.co.uk/mygreatdiscovery/post/Creating-tooltips-using-data-annotations-in-ASPNET-MVC.aspx

 public static MvcHtmlString RequiredLabelFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression) { var metaData = ModelMetadata.FromLambdaExpression(expression, helper.ViewData); string htmlFieldName = ExpressionHelper.GetExpressionText(expression); string labelText = metaData.DisplayName ?? metaData.PropertyName ?? htmlFieldName.Split('.').Last(); if (metaData.IsRequired) labelText += "<span class=\"required-field\">*</span>"; if (String.IsNullOrEmpty(labelText)) return MvcHtmlString.Empty; var label = new TagBuilder("label"); label.Attributes.Add("for", helper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName)); label.InnerHtml = labelText; return MvcHtmlString.Create(label.ToString()); } 

使用帮助器将样式类添加到标签

 public static MvcHtmlString RequiredLabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object htmlAttributes) { var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData); var resolvedLabelText = metadata.DisplayName ?? metadata.PropertyName; if (!metadata.IsRequired) { return html.LabelFor(expression, resolvedLabelText, htmlAttributes); } var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes); if (attributes == null) { return html.LabelFor(expression, resolvedLabelText, htmlAttributes); } const string requiredClass = "required-label"; if (attributes.ContainsKey("class")) { var classList = attributes["class"].ToString().Split(' ').ToList(); classList.Add(requiredClass); attributes["class"] = string.Join(" ", classList); } else { attributes.Add("class", requiredClass); } return html.LabelFor(expression, resolvedLabelText, attributes); } 

那么你可以风格的类:

 .required-label::after { content : "*" } 

我从一些其他职位一起蹒跚起来:

它适用于我,因为labelfor后跟一个input加一个范围(标签的input和validation范围)

 input[data-val-required]+span:before { content: "*"; font-weight: bold; color: red; position:relative; top:-34px; left:-12px; font-size:14pt; } 

根据Renato Saito和评论的上述回答,以及添加$(document).ready并检查以确保我们不添加多个星号(我在某些字段中获得了一些理由),我有这个:

 // Add asterisks to required fields $(document).ready(function() { $("[data-val-required]").each(function () { var label = $('label[for="' + $(this).attr("id") + '"]'); var asterisksHtml = '<span style="color:red">&nbsp;*</span>'; if (label.text().length > 0 && label.html().indexOf(asterisksHtml) === -1) { label.append(asterisksHtml); } }); });