I have the following
<label for="Forename">Forename</label>
<%= Html.TextBoxFor(m => m.Customer.Name.Forename) %>
the problem with this is that this is rendered as
<label for="Forename">Forename</label>
<input type="text" value="" name="Customer.Name.Forename" id="Customer_Name_Forename">
not what I want ofc.
I would like an extension to render the label correctly (i.e. with the for="" attribute having the value of the input id), is there anything in MVC 2 that does this nativly before I go writing my own extension?
Label is a label extension that allows you to display text on a web page.
The HTML <label> for Attribute is used to specify the type of form element a label is bound to. Syntax: <label for="element_id"> Attribute Values: It contains the value i.e element_id which specify the id of the element that the label is bound to.
ASP.NET MVC: ValidationMessageFor The Html. ValidationMessageFor() is a strongly typed extension method. It displays a validation message if an error exists for the specified field in the ModelStateDictionary object. Visit MSDN to know all the overloads of ValidationMessageFor() method.
<%= Html.LabelFor(m => m.Customer.Name.Forename) %>
<%= Html.TextBoxFor(m => m.Customer.Name.Forename) %>
The following will allows overriding the default display name, the alternative to using the below is to vandalise your model using a [DisplayName]
attribute
Usage
<%= Html.LabelFor(m => m.Customer.Name.Forename, "First Name")%>
Code
namespace System.Web.Mvc.Html
{
public static class LabelExtensions
{
public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, string displayName)
{
return LabelHelper(html, ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, html.ViewData), ExpressionHelper.GetExpressionText(expression), displayName);
}
internal static MvcHtmlString LabelHelper(HtmlHelper html, ModelMetadata metadata, string htmlFieldName, string displayName)
{
string str = displayName ?? metadata.DisplayName ?? (metadata.PropertyName ?? htmlFieldName.Split(new char[] { '.' }).Last<string>());
if (string.IsNullOrEmpty(str))
{
return MvcHtmlString.Empty;
}
TagBuilder builder = new TagBuilder("label");
builder.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(htmlFieldName));
builder.SetInnerText(str);
return MvcHtmlString.Create(builder.ToString(TagRenderMode.Normal));
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With