How can I modify LabelFor to display an asterisk on required fields?
I want to cr开发者_运维技巧eate an extension method for HtmlHelper
that allows me to create a LabelFor
a property display an asterisk after it if it is a required field. How can I do that?
public class Foo
{
[Required]
public string Name { get; set; }
}
Html.LabelFor(o => o.Name) // Name*
You can add an asterisk to a required field purely through CSS.
First, create a CSS class for it:
.required::after
{
content: "*";
font-weight: bold;
color: red;
}
This will append a red asterisk to any element with the "required" class.
Then, in your view, simply add the new class to your label:
@Html.LabelFor(m => m.Name, new { @class="required" })
Even better might be a custom HTML Helper that discerns if the field has a [Required] attribute, and if so, adds the required
CSS class.
Here is an blog post that describes how to do this.
To give you a small example modified from the site above (note - I have not compiled/tested this):
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));
}
}
}
I did that way because my required fields must be dynamic (defined in a configuration file)
Add at the end of your View:
<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>
Here is my solution based on Adam Tuliper's answer but modified to work with Bootstrap and also allow the usage of custom attributes.
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());
}
}
Then, I call it from my view like this:
@Html.RequiredLabelFor(model => model.Category, new { @class = "control-label col-md-3" })
P.S. Make sure you don't forget to include your namespace in your view.
see this post here - should contain most of what you need 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());
}
Use helper to add style class to the label
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);
}
Then you can style the class:
.required-label::after { content : "*" }
I hobbled this together from some other posts:
It works for me since the labelfor is followed by an input plus a span (the input the label is for, and the validation span)
input[data-val-required]+span:before {
content: "*";
font-weight: bold;
color: red;
position:relative;
top:-34px;
left:-12px;
font-size:14pt;
}
Based on the above answer by Renato Saito along with the comments, as well as adding $(document).ready and checking to make sure that we are not adding more than one asterisks (I'm getting that on some of my fields for some reason), I have this:
// 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"> *</span>';
if (label.text().length > 0 && label.html().indexOf(asterisksHtml) === -1) {
label.append(asterisksHtml);
}
});
});
Though this doesn't require modifying the LabelFor, it is the simplest I can think of which only requires 1 line in your ViewModel:
public class FooViewModel
{
[Required(ErrorMessage = "Name is required")]
[Display(Name ="Name*")]
public string Name { get; set; }
}
Html.LabelFor(o => o.Name)
Best working for me in MVC with multiple field types
$('input[type=text], input[type=password], input[type=email], input[type=tel], select').each(function () {
var req = $(this).attr('data-val-required');
if (undefined != req) {
var label = $('label[for="' + $(this).attr('name') + '"]');
var text = label.text();
if (text.length > 0) {
label.append('<span style="color:red"> *</span>');
}
}
});
Add a decorated glyphicon icon after a mandatory field (defined via data annotation [Required]) using a helper extension preserving both internalizations/translations labels and html attributes
1. Create Folder "Helpers" and add a new controller "Helper.cs"
using System;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Mvc;
namespace WIPRO.Helpers
{
public static class Helpers
{
public static MvcHtmlString LabelForRequired<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression, string translatedlabelText, 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 = translatedlabelText + "<span class=\"required\" style=\"color:orange;\"> <span style=\"font-size: 0.4em; vertical-align: super;\" class=\"glyphicon glyphicon-asterisk\" data-unicode=\"270f\"></span></span>";
}
else
{
labelText = translatedlabelText;
}
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());
}
}
}
2. In your view
@using WIPRO.Helpers
@Html.LabelForRequired(model => model.Test,"Translated text", htmlAttributes: new { @class = "control-label col-md-2" })
in place of
@Html.LabelFor(model => model.Test,"Translated text", htmlAttributes: new { @class = "control-label col-md-2" })
Hope it helps ;-)
I wanted to create a Label that displayed an asterix when a property was required. But somehow the metadata.IsRequired
property always returned false, even though the [Required]
attribute was set and was working in the Model Validation. So I used the AssociatedMetadataTypeTypeDescriptionProvider
public static MvcHtmlString CustomLabelFor<TModel, TValue>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TValue>> expression, object htmlAttributes = null)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var descriptor = new AssociatedMetadataTypeTypeDescriptionProvider(metadata.ContainerType).GetTypeDescriptor(metadata.ContainerType).GetProperties().Find(metadata.PropertyName, true);
var required = (new List<Attribute>(descriptor.Attributes.OfType<Attribute>())).OfType<RequiredAttribute>().FirstOrDefault();
//get the normal labelfor
var label = htmlHelper.LabelFor(expression, htmlAttributes);
//create the extra span with the asterix in there is a required property
if (required != null)
{
var span = new TagBuilder("span");
span.MergeAttribute("class", "text-danger font-weight-bold");
//render the span
StringBuilder sb = new StringBuilder();
sb.Append(span.ToString(TagRenderMode.StartTag));
sb.Append("*");
sb.Append(span.ToString(TagRenderMode.EndTag));
return MvcHtmlString.Create(label.ToHtmlString() + " " + sb.ToString());
}
else
{
return label;
}
}
Usage
@Html.CustomLabelFor(m => m.Title)
Post a general solution:
Here is a general format to use Bootstrap:
<div class="form-group row">
<label class="col-md-3 label-control" asp-for="FacilityCode"></label>
<div class="col-md-9">
<input asp-for="FacilityCode" class="form-control" placeholder="@Localizer["Facility Code"]" />
<span asp-validation-for="FacilityCode" class="text-danger"></span>
</div>
</div>
Here is generated code by default TagHelper:
<div class="form-group row">
<label class="col-md-3 label-control" for="FacilityCode">Example Label </label>
<div class="col-md-9">
<input class="form-control" placeholder="Facility Code" type="text" data-val="true" data-val-length="The field Institution (Community) must be a string with a maximum length of 5." data-val-length-max="5" data-val-required="The Institution (Community) field is required." id="FacilityCode" maxlength="5" name="FacilityCode" value="12345">
<span class="text-danger field-validation-valid" data-valmsg-for="FacilityCode" data-valmsg-replace="true"></span>
</div>
</div>
what I need is to append <span style="color:red;">*</span>
to all required fields, instead of using TagHelper
everywhere.
// append red star to required fields
$(document).ready(function () {
$('input[data-val-required]')
.closest(".form-group")
.find("label.label-control")
.append("<span style='color:red;'>*</span>");
});
精彩评论