Step 1: Create a helper class in the models folder and add this code:
- public static MvcHtmlString CustomLabelFor < TModel, TValue > (this HtmlHelper < TModel > html, Expression < Func < TModel, TValue >> expression) {
- var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
- var htmlFieldName = metadata.DisplayName;
- var IsRequired = metadata.IsRequired;
- var strHtml = "";
- if (IsRequired == true) {
- strHtml = "<label>" + htmlFieldName + " <i class='required'>*</i></label>";
- } else {
- strHtml = "<label>" + htmlFieldName + "</label>";
- }
- return MvcHtmlString.Create(strHtml.ToString());
- }
Step 2: Use this line of code in you view to get the helper class.
- @using ProjectName.Models
Step 3: Now you can use replace the LabelFor field with the custom label created as shown below:
- @Html.CustomLabelFor(x => x.user.FirstName)
Hope this is helpful,please revert back if u hav any suggestions or clarifications.