BrunoLM
BrunoLM

Reputation: 100361

How to write a custom @Html.ControlFor(o => o.Property)?

I want to create a custom method, to be able to call it as

@Html.PaginationFor(o => o.List)

I started looking at reflector, but I don't know exactly what it is doing over there. I tried:

public static MvcHtmlString PaginationFor<TModel, TProperty>(this Html<TModel> html,
    Expression<Func<TModel, TProperty>> expression)
{
    var propertyValue = ????????
    return html.Partial("View", propertyValue);
}

How do I extract the property value from the expression to pass as a model of the partial view?

Upvotes: 3

Views: 359

Answers (2)

John Farrell
John Farrell

Reputation: 24754

public static MvcHtmlString PaginationFor<TModel, TProperty>(this HtmlHelper<TModel> html,
    Expression<Func<TModel, TProperty>> expression) {

    var func = expression.Compile();

    var propertyValue = func(html.ViewData.Model);
    return html.Partial("View", propertyValue);
}

Upvotes: 0

Darin Dimitrov
Darin Dimitrov

Reputation: 1039120

public static MvcHtmlString PaginationFor<TModel, TProperty>(
    this HtmlHelper<TModel> html,
    Expression<Func<TModel, TProperty>> expression
)
{
    TModel model = html.ViewData.Model;
    var metaData = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
    var propertyValue = metaData.Model; // This will be of type TProperty
    return html.Partial("View", propertyValue);
}

Upvotes: 3

Related Questions