How to give custom name to HTML helper Label in ASP.NET MVC?

Viewed 58

How can I give custom name to HTML helper label? And how to apply style to it?

I want the label output to be like this:

enter image description here

In HTML we can achieve like this:

<label class="Color">Degree Title<span class="Text-danger">*</span><label> 

But how can I achieve this through HTML helper Method Labelfor in ASP.NET MVC ?

I tried this code, but it display same text on browser Which I write here in quotes Degree Level <span class='Text-danger'>*</span> :

@Html.LabelFor(model => model.Level, "Degree Level <span class='Text-danger'>*</span> ", htmlAttributes: new { @class = "control-label"}) 

How to modify it?

1 Answers

You can try to use some custom HTML helper:

public static class LabelExtensions
{
    public static MvcHtmlString LabelForCustom<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string labelText, object htmlAttributes)
    {
        var text = html.LabelFor(expression, labelText, htmlAttributes);
        return new MvcHtmlString("<div>" + text + "<span class=\"Text-danger\">*</span>" + "</div>");
    }
}

And call it from a .cshtml:

@Html.LabelForCustom(model => model.Level, "Degree Level ", htmlAttributes: new { @class = "control-label" })

And it is necessary to add @using on top of the .cshtml:

@using namespace_where_LabelExtensions_class_is_defined 

NOTE:

If you want to include the <span> tag exactly inside the <label> you will need to generate all the HTML content after removing the var text = html.LabelFor(expression, labelText, htmlAttributes); line.

Creating HTML Helpers with Extension Methods

Related