我有以下内容
<label for="Forename">Forename</label>
<%= Html.TextBoxFor(m => m.Customer.Name.Forename) %>
Run Code Online (Sandbox Code Playgroud)
这个问题是这个呈现为
<label for="Forename">Forename</label>
<input type="text" value="" name="Customer.Name.Forename" id="Customer_Name_Forename">
Run Code Online (Sandbox Code Playgroud)
不是我想要的.
我想要一个扩展来正确呈现标签(即使用具有输入id值的for =""属性),在我编写自己的扩展之前,MVC 2中有什么东西可以做到这一点吗?
svi*_*nto 13
<%= Html.LabelFor(m => m.Customer.Name.Forename) %>
<%= Html.TextBoxFor(m => m.Customer.Name.Forename) %>
Run Code Online (Sandbox Code Playgroud)
Jai*_*han 11
以下将允许覆盖默认显示名称,使用下面的替代方法是使用[DisplayName]属性破坏模型
用法
<%= Html.LabelFor(m => m.Customer.Name.Forename, "First Name")%>
Run Code Online (Sandbox Code Playgroud)
码
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));
}
}
}
Run Code Online (Sandbox Code Playgroud)