Just write a regular <label> element in plain HTML:
<label>My Label:</label>
If you want to display the for="" attribute and accurately visualize the name of the control, use this extension method:
using System; using System.Linq.Expressions; using System.Web.Mvc; namespace MvcLibrary.Extensions { public static class HtmlExtensions { public static MvcHtmlString FieldIdFor<TModel, TValue>( this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression) { string htmlFieldName = ExpressionHelper.GetExpressionText(expression); string inputFieldId = html.ViewContext.ViewData. TemplateInfo.GetFullHtmlFieldId(htmlFieldName); return MvcHtmlString.Create(inputFieldId); } } }
Then you can use in your view like this:
<label for="<%= Html.FieldIdFor(m => m.EmailAddress) %>">E-mail address:</label> <%= Html.TextBoxFor(m => m.EmailAddress) %>
Other posts cover different approaches, they are all equally valid, and you are engaged in personal preference. I personally prefer to write <label> as plain HTML, as it gives developers more flexibility when changing markup, adding extra attributes like CSS classes, etc. I also believe that the text of the label is a matter of consideration and should not be framed in the ViewModel class, but this is only my personal opinion / preference, I know that some people here will not agree with me and this fine :-)
source share