【问题标题】:Why I cant use Html.RenderPartial in razor helper view File in App_Code Folder?为什么我不能在 App_Code 文件夹中的剃刀助手视图文件中使用 Html.RenderPartial?
【发布时间】:2012-09-12 17:08:12
【问题描述】:

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>

视图/共享文件夹中的简单局部视图:

部分.cshtml

<h1>Me is Partial</h1>

编译器抛出错误:

CS1061: 'System.Web.WebPages.Html.HtmlHelper' enthält keine 定义 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 Using-Directive oder ein Assemblyverweis?)。

但如果我在 MyView.cshtml 中调用 Html.RenderPartial 一切正常。

我想我必须更改一些 web.configs,因为 MyView 中的 HtmlHelper 取自 System.Web.Mvc,而 MyHelper.cshtml 中的 HtmlHelper 取自 System.Web.WebPages。

我该如何解决这个问题?

【问题讨论】:

    标签: razor html-helper renderpartial app-code


    【解决方案1】:

    Html 是网页的属性,因此您只能在视图内部访问它。 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>
    

    【讨论】:

    • 不对我不起作用。首先是一个简单的语法错误,因为 '{' '}' 删除它们后,由于引用不明确,我得到一个错误。 ['HtmlHelper' 是 'System.Web.WebPages.Html.HtmlHelper' 和 'System.Web.Mvc.HtmlHelper' 之间的模糊引用
    • 您可以在函数中明确指定类型。另请注意,您应该包含 @using System.Web.Mvc.Html 而不是 @using System.Web.Mvc 请参阅我的更新答案。
    • 我也试过了 @using mvc = System.Web.Mvc @helper SimpleHelper(string inputFor, mvc.HtmlHelper wvp){ &lt;span&gt;@inputFor&lt;/span&gt; wvp.RenderPartial("Partial"); }
    • 请查看我的更新答案并使用那里显示的确切代码
    • 你知道问题出在哪里吗?我已经尝试过完全相同的代码,但我总是遇到同样的错误,但我从未构建它。这次我构建了它,但突然警告和错误消息消失了。谢谢!
    猜你喜欢
    • 1970-01-01
    • 2011-06-19
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 2013-02-22
    • 1970-01-01
    • 1970-01-01
    • 2015-07-13
    相关资源
    最近更新 更多