从 Razor 声明式视图使用 MVC HtmlHelper 扩展 [英] Using MVC HtmlHelper extensions from Razor declarative views
问题描述
我试图在我的 App_Code 文件夹中为 MVC 3 RTM 项目创建一个 Razor 声明性助手.
I was trying to create a Razor declarative helper in my App_Code folder for an MVC 3 RTM project.
我遇到的问题是 MVC HtmlHelper 扩展(如 ActionLink)不可用.这是因为编译的帮助程序派生自 System.Web.WebPages.HelperPage
,虽然它公开了一个 Html
属性,但它的类型是 System.Web.WebPages.HtmlHelper
而不是 System.Web.Mvc.HtmlHelper
.
The problem I ran into was that the MVC HtmlHelper extensions, like ActionLink, aren't available. This is because the compiled helpers derive from System.Web.WebPages.HelperPage
, and though it exposes an Html
property, its of type System.Web.WebPages.HtmlHelper
rather than System.Web.Mvc.HtmlHelper
.
我遇到的错误类型的一个例子是:
An example of the kind of error I was getting is:
'System.Web.Mvc.HtmlHelper' 没有包含ActionLink"的定义并且没有扩展方法ActionLink"接受类型的第一个参数'System.Web.Mvc.HtmlHelper' 可以是找到了(您是否缺少使用指令或程序集引用?)
'System.Web.Mvc.HtmlHelper' does not contain a definition for 'ActionLink' and no extension method 'ActionLink' accepting a first argument of type 'System.Web.Mvc.HtmlHelper' could be found (are you missing a using directive or an assembly reference?)
我唯一的解决方案是创建我自己的 HelperPage 并覆盖 Html 属性:
My only solution has been to create my own HelperPage and override the Html property:
using System.Web.WebPages;
public class HelperPage : System.Web.WebPages.HelperPage
{
// Workaround - exposes the MVC HtmlHelper instead of the normal helper
public static new HtmlHelper Html
{
get { return ((System.Web.Mvc.WebViewPage) WebPageContext.Current.Page).Html; }
}
}
然后我必须在每个助手的顶部写下以下内容:
I then have to write the following at the top of every helper:
@inherits FunnelWeb.Web.App_Code.HelperPage
@using System.Web.Mvc
@using System.Web.Mvc.Html
@helper DoSomething()
{
@Html.ActionLink("Index", "Home")
}
在 MVC 3 中是不是要这么难,还是我做错了什么?
Is it meant to be this hard in MVC 3, or am I doing something wrong?
推荐答案
看一看 Marcind
对这个问题的回答.您遇到的是将声明性视图放在 App_Code
文件夹中的限制.
Take a look at Marcind
's answer to this question. What you're experiencing is a limitation of putting declarative views in the App_Code
folder.
将你的助手放在 App_Code 中是有效的但有一定的局限性影响某些 MVC 场景(对于示例:无法访问标准 MVChtml.帮手)
Putting your helpers in App_Code works but has certain limitations that impact certain MVC scenarios (for example: no access to standard MVC Html. helpers)
这篇关于从 Razor 声明式视图使用 MVC HtmlHelper 扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!