Skip to content

Instantly share code, notes, and snippets.

@ilovejs
Created July 15, 2015 01:17
Show Gist options
  • Save ilovejs/5a442a7a1c73aefb9683 to your computer and use it in GitHub Desktop.
Save ilovejs/5a442a7a1c73aefb9683 to your computer and use it in GitHub Desktop.
MVC Mandatory Field Label For Helper
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.WebPages;
namespace RegistrationSample.UI.Web.mvcHelper
{
/// <summary>
/// Mandatory Field Extension
/// @Html.MandatoryLabelFor(m => m.JobTitle, @<span style='color: red;'>*</span>)
/// </summary>
public static class LabelExtensions
{
public static MvcHtmlString MandatoryLabelFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> lambdaExpr, //m => m.JobTitle
Func<object, HelperResult> template //@<span>Hello World</span>
)
{
var htmlFieldName = ExpressionHelper.GetExpressionText(lambdaExpr);
var fullHtmlFieldName = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName);
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(lambdaExpr, htmlHelper.ViewData);
string labelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
var label = new TagBuilder("label");
label.Attributes["for"] = TagBuilder.CreateSanitizedId(fullHtmlFieldName);
label.InnerHtml = labelText + " " + template(null).ToHtmlString();
return MvcHtmlString.Create(label.ToString());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment