是否可以使用 Razor 创建通用的 @helper 方法? [英] Is it possible to create a generic @helper method with Razor?

查看:29
本文介绍了是否可以使用 Razor 创建通用的 @helper 方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Razor 中编写一个如下所示的助手:

I am trying to write a helper in Razor that looks like the following:

@helper DoSomething<T, U>(Expression<Func<T, U>> expr) where T : class

不幸的是,解析器认为 <T 是 HTML 元素的开头,我最终出现了语法错误.是否可以使用作为通用方法的 Razor 创建帮助程序?如果是这样,语法是什么?

Unfortunately, the parser thinks that <T is the beginning of an HTML element and I end up with a syntax error. Is it possible to create a helper with Razor that is a generic method? If so, what is the syntax?

推荐答案

不,这目前是不可能的.您可以改为编写一个普通的 HTML 帮助程序.

No, this is not currently possible. You could write a normal HTML helper instead.

public static MvcHtmlString DoSomething<T, U>(
    this HtmlHelper htmlHelper, 
    Expression<Func<T, U>> expr
) where T : class
{
    ...
}

然后:

@(Html.DoSomething<SomeModel, string>(x => x.SomeProperty))

或者如果您将模型作为第一个通用参数:

or if you are targeting the model as first generic argument:

public static MvcHtmlString DoSomething<TModel, TProperty>(
    this HtmlHelper<TModel> htmlHelper, 
    Expression<Func<TModel, TProperty>> expr
) where TModel : class
{
    ...
}

这将允许您像这样调用它(当然假设您的视图是强类型的,但这是一个安全的假设,因为无论如何所有视图都应该是强类型的:-)):

which will allow you to invoke it like this (assuming of course that your view is strongly typed, but that's a safe assumption because all views should be strongly typed anyways :-)):

@Html.DoSomething(x => x.SomeProperty)

这篇关于是否可以使用 Razor 创建通用的 @helper 方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆