App_Code文件夹中的简单Razor助手:
MyHelper.cshtml
@using System.Web.Mvc
@helper SimpleHelper(string inputFor){
<span>@inputFor</span>
Html.RenderPartial("Partial");
}
视图/共享文件夹中的简单视图:
MyView.cshtml
<html>
<head
</head>
<body>
@WFRazorHelper.SimpleHelper("test")
</body>
</html>
视图/共享文件夹中的简单部分视图:
Partial.cshtml
<h1>Me is Partial</h1>
编译器抛出错误:
CS1061:'System.Web.WebPages.Html.HtmlHelper'enthältkeine定义 für'RenderPartial',und es konnte keine Erweiterungsmethode 'RenderPartial'gefunden werden,die ein erstes Argument vom Typ 'System.Web.WebPages.Html.HtmlHelper'akzeptiert(Fehlt eine) 使用-Direktive oder ein Assemblyverweis?)。
但如果我在MyView.cshtml中调用Html.RenderPartial,一切正常。
我想我必须更改一些web.configs,因为MyView中的HtmlHelper取自System.Web.Mvc而MyHelper.cshtml中的HtmlHelper取自System.Web.WebPages。
我该如何解决这个问题?
答案 0 :(得分:13)
Html
是WebPage的属性,因此您只能在视图内访问它。 App_Code文件夹中的自定义帮助程序无权访问它。
因此,如果您需要在{}中使用它,则需要传递HtmlHelper
作为参数:
@using System.Web.Mvc.Html
@helper SimpleHelper(System.Web.Mvc.HtmlHelper html, string inputFor)
{
<span>@inputFor</span>
html.RenderPartial("Partial");
}
然后通过从视图中传递HtmlHelper实例来调用自定义帮助程序:
<html>
<head>
</head>
<body>
@WFRazorHelper.SimpleHelper(Html, "test")
</body>
</html>