Asp.net-Mvc-2
Asp.net MVC 標籤為
我有以下
<label for="Forename">Forename</label> <%= Html.TextBoxFor(m => m.Customer.Name.Forename) %>問題在於這被呈現為
<label for="Forename">Forename</label> <input type="text" value="" name="Customer.Name.Forename" id="Customer_Name_Forename">不是我想要的。
我想要一個擴展來正確呈現標籤(即使用具有輸入 id 值的 for="" 屬性),在我編寫自己的擴展之前,MVC 2 中有什麼可以自然地做到這一點嗎?
<%= Html.LabelFor(m => m.Customer.Name.Forename) %> <%= Html.TextBoxFor(m => m.Customer.Name.Forename) %>
下面將允許覆蓋預設顯示名稱,使用下面的替代方法是使用
[DisplayName]屬性破壞您的模型用法
<%= Html.LabelFor(m => m.Customer.Name.Forename, "First Name")%>程式碼
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)); } } }