来自道具的Asp.net Mvc2 LabelFor和DisplayName

时间:2010-01-19 11:30:13

标签: asp.net-mvc asp.net-mvc-2

上下文=>

${Html.CheckBoxFor(x => x.Foos[i].Checked)}
${Html.LabelFor(x => x.Foos[i].Checked)}

问题是 - 我无法提供基于Foo.Name的标签文本。

是否有开箱即用的方法如何修改元数据,传入lambda x => x.Name来改变它?

正在创建另一个HmtlHelper扩展方法

LabelFor(this htmlhelper, [lambda], value, htmlattribs)

唯一的方法?


Related issue

1 个答案:

答案 0 :(得分:3)

不管怎么说。解决方法是可以接受的这个问题不是showstopper =>

 public static MvcHtmlString LabelFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression, 
            string labelText, object htmlAttributes) where TModel : class
        {
            TagBuilder builder = new TagBuilder("label");
            builder.MergeAttributes(new RouteValueDictionary(htmlAttributes)); // to convert an object into an IDictionary
            string value = ExpressionHelper.GetExpressionText(expression); ;
            builder.InnerHtml = labelText;
            //the replaces shouldnt be necessary in the next statement, but there is a bug in the MVC framework that makes them necessary.
            builder.Attributes.Add("for", html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(value).Replace('[', '_').Replace(']', '_'));
            return MvcHtmlString.Create(builder.ToString(TagRenderMode.Normal));
        }