Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to specify ID for an Html.LabelFor<> (MVC Razor) [duplicate]

Possible Duplicate:
Client Id for Property (ASP.Net MVC)

Is there a way to make Razor render an ID attribute for a Label element when using the Html.LabelFor<> helper?

Example:

.cshtml page
@using (Html.BeginForm())
{
@Html.LabelFor(m => m.Foo)
@Html.TextBoxFor(m => m.Foo)
}

Rendered page

<form ...>
<label for="Foo" id="Label_Foo" />
<input type="text" name="Foo" id="Foo" />
</form>

FYI - The sole reason I'm wanting to add an ID to the Label is for CSS design. I'd prefer to reference the Label by an ID rather than wrapping the Label within a block (i.e. div) and then styling the block.

like image 447
Jed Avatar asked Jun 06 '11 16:06

Jed


People also ask

What is HTML LabelFor?

Html.Label gives you a label for an input whose name matches the specified input text (more specifically, for the model property matching the string expression): // Model public string Test { get; set; } // View @Html. Label("Test") // Output <label for="Test">Test</label>

What is HTML EditorFor in MVC?

ASP.NET MVC includes the method that generates HTML input elements based on the datatype. The Html. Editor() or Html. EditorFor() extension methods generate HTML elements based on the data type of the model object's property.


2 Answers

Unfortunately there is no built-in overload of this helper that allows you to achieve this.

Fortunately it would take a couple of lines of code to implement your own:

public static class LabelExtensions
{
    public static MvcHtmlString LabelFor<TModel, TValue>(
        this HtmlHelper<TModel> html, 
        Expression<Func<TModel, TValue>> expression, 
        object htmlAttributes
    )
    {
        return LabelHelper(
            html,
            ModelMetadata.FromLambdaExpression(expression, html.ViewData),
            ExpressionHelper.GetExpressionText(expression),
            htmlAttributes
        );
    }

    private static MvcHtmlString LabelHelper(
        HtmlHelper html, 
        ModelMetadata metadata,
        string htmlFieldName, 
        object htmlAttributes
    )
    {
        string resolvedLabelText = metadata.DisplayName ?? metadata.PropertyName ?? htmlFieldName.Split('.').Last();
        if (string.IsNullOrEmpty(resolvedLabelText))
        {
            return MvcHtmlString.Empty;
        }

        TagBuilder tag = new TagBuilder("label");
        tag.Attributes.Add("for", TagBuilder.CreateSanitizedId(html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(htmlFieldName)));
        tag.MergeAttributes(new RouteValueDictionary(htmlAttributes));
        tag.SetInnerText(resolvedLabelText);
        return MvcHtmlString.Create(tag.ToString(TagRenderMode.Normal));
    }
}

and once brought into scope use this helper in your view:

@Html.LabelFor(m => m.Foo, new { id = "Foo" })
@Html.TextBoxFor(m => m.Foo)

Remark: because now it is up to you to manage HTML ids, make sure that they are unique throughout the entire document.

Remark2: I have shamelessly plagiarized and modified the LabelHelper method from the ASP.NET MVC 3 source code.

like image 107
Darin Dimitrov Avatar answered Sep 20 '22 07:09

Darin Dimitrov


And for the normal label @Html.Label(), you can do it like this:

public static HtmlString Label(this HtmlHelper helper, string target = "", string text = "", string id = "")
{
    return new HtmlString(string.Format("<label id='{0}' for='{1}'>{2}</label>", id, target, text));
}
like image 38
Actionman Avatar answered Sep 22 '22 07:09

Actionman