Asp.net MVC Label For

会有一股神秘感。 提交于 2019-12-09 05:34:45

问题


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?


回答1:


<%= Html.LabelFor(m => m.Customer.Name.Forename) %>
<%= Html.TextBoxFor(m => m.Customer.Name.Forename) %>



回答2:


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));
        }
    }
}


来源:https://stackoverflow.com/questions/2595947/asp-net-mvc-label-for

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!