Domanda

I am trying to use Expression<Func<TModel, TProperty>> expression, sent in to my helper class.

I want to pull the value form it and render it in a html string. I can't seem to get it working i currently have:

  public static MvcHtmlString TextboxGroupStaticFor<TModel, TProperty>(
        this HtmlHelper<TModel> html,
        Expression<Func<TModel, TProperty>> expression,
        BootstrapInputSizes? width = BootstrapInputSizes.Defalut
        )
    {
        var placeholder = string.Empty;
        if (html.ViewData.ModelMetadata.AdditionalValues.ContainsKey("placeholder"))
        {
            placeholder = html.ViewData.ModelMetadata.AdditionalValues["placeholder"] as string;
        }


        var sb = new StringBuilder();

        sb.AppendLine("<div class=\"form-group\">");
        sb.AppendLine(html.LabelFor(expression).ToHtmlString());
        sb.AppendLine("<p class=\"form-control-static\">" + " " + "</p>");
        sb.AppendLine("</div>");
        return new MvcHtmlString(sb.ToString());
    }

Called using: @Html.TextboxGroupStaticFor(x=> x.Name);

But can't work out how to do expression.value or something like that?

UPDATE

I found this works

 Func<TModel, TProperty> method = expression.Compile();

            TProperty value = method(html.ViewData.Model);

Is this a good way e.g performance wise?

È stato utile?

Soluzione

I believe you're looking for:

sb.AppendLine(html.LabelFor(expression.Compile()()).ToHtmlString());
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top