是否可以使用 Razor 创建通用的 @helper 方法?

编程入门 行业动态 更新时间:2024-10-24 06:38:35
本文介绍了是否可以使用 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 方法?

本文发布于:2023-11-16 22:02:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1607645.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:可以使用   方法   Razor   helper

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!