开发者

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

开发者 https://www.devze.com 2023-03-21 02:04 出处:网络
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:

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&l开发者_Go百科t;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?


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


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

精彩评论

暂无评论...
验证码 换一张
取 消