Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Unfortunately there is no built-in overload of this helper that allows you to achieve this. </p> <p>Fortunately it would take a couple of lines of code to implement your own:</p> <pre><code>public static class LabelExtensions { public static MvcHtmlString LabelFor&lt;TModel, TValue&gt;( this HtmlHelper&lt;TModel&gt; html, Expression&lt;Func&lt;TModel, TValue&gt;&gt; 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)); } } </code></pre> <p>and once brought into scope use this helper in your view:</p> <pre><code>@Html.LabelFor(m =&gt; m.Foo, new { id = "Foo" }) @Html.TextBoxFor(m =&gt; m.Foo) </code></pre> <p>Remark: because now it is up to you to manage HTML ids, make sure that they are unique throughout the entire document.</p> <p>Remark2: I have shamelessly plagiarized and modified the <code>LabelHelper</code> method from the ASP.NET MVC 3 source code.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload