我正在尝试在 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 方法?
发布评论