public class FooViewModel
{
[Required(ErrorMessage = "Name is required")]
[Display(Name ="Name*")]
public string Name { get; set; }
}
Html.LabelFor(o => o.Name)
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;
}
}
<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>