asp.net-mvcasp.net-mvc-2

Asp.net Mvc2 LabelFor and DisplayName from prop


Context =>

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

Problem is - i can't provide label text based on Foo.Name.

Is there out of the box method of how to modify metadata, passing in lambda x=>x.Name to change it?

Is creating another HmtlHelper extension method

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

the only way?


Related issue


Solution

  • Eh, whatever. Workaround is acceptable. This issue ain't 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));
            }