是否有可能创建一个剃刀一般@helper方法? [英] Is it possible to create a generic @helper method with Razor?

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

问题描述

我试图写一个剃刀帮手,看起来像以下内容:

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

不幸的是,解析器认为&LT;吨是一个HTML元素的开始,我结束了一个语法错误。是否有可能创建一个剃刀助手是一个通用的方法是什么?如果是这样,什么是语法?

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 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 T : 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)

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

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