I have a custom html Helper class like this below,
public static class LabelWithAstrickHelper
{
public static MvcHtmlString LabelWithAstrick<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object htmlAttributes)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
string resolvedLabelText = metadata.DisplayName ?? metadata.PropertyName;
if (metadata.IsRequired)
{
resolvedLabelText += "*";
// resolvedLabelText += "<span style='color:red;'>*</span>";
}
return LabelExtensions.LabelFor<TModel, TValue>(html, expression, resolvedLabelText, htmlAttributes);
}
}
I used it like below in my view.
@Html.LabelWithAstrick(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })
Now this will Show 'astrick' in black color, but I want to display this 'astrick' sign in red color.
please suggest How to do this.
Since you want to style the label text and the associated asterisk differently, then you cannot use the inbuilt LabelFor()
method (the HtmlHelper
methods encode the vale of the label text.
Instead you need to generate you own html in the method.
public static MvcHtmlString LabelWithAstrick<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, object htmlAttributes)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
var name = ExpressionHelper.GetExpressionText(expression);
string text = metadata.DisplayName ?? metadata.PropertyName ?? name.Split('.').Last();
// Build 2 span elements containing text and the styled asterisk
StringBuilder innerHtml = new StringBuilder();
TagBuilder span = new TagBuilder("span");
span.InnerHtml = text;
innerHtml.Append(span.ToString());
if (metadata.IsRequired)
{
span = new TagBuilder("span");
span.InnerHtml = "*";
span.MergeAttribute("style", "color:red;"); // see notes
innerHtml.Append(span.ToString());
}
// Create the label element and add the 2 span elements
TagBuilder label = new TagBuilder("label");
label.Attributes.Add("for", TagBuilder.CreateSanitizedId(html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name)));
RouteValueDictionary attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);
label.MergeAttributes(attributes, replaceExisting: true);
label.InnerHtml = innerHtml.ToString();
return new MvcHtmlString(label.ToString());
}
Note that I hard-coded an inline style for the asterisk as per your code, however I would recommend you use a class name instead using span.AddCssClass("....");
and create a css definition for that class name to give you more flexibility.