Why I cant use Html.RenderPartial in razor helper view File in App_Code Folder?

孤者浪人 提交于 2020-01-23 05:49:04

问题


Simple Razor Helper in App_Code Folder:

MyHelper.cshtml

@using System.Web.Mvc

@helper SimpleHelper(string inputFor){
    <span>@inputFor</span>
    Html.RenderPartial("Partial");
}

Simple View in Views/Shared Folder:

MyView.cshtml

<html>
    <head

    </head>
    <body>
        @WFRazorHelper.SimpleHelper("test")
    </body>
</html>

Simple Partial View in Views/Shared Folder:

Partial.cshtml

<h1>Me is Partial</h1>

Compiler throws an Error:

CS1061: 'System.Web.WebPages.Html.HtmlHelper' enthält keine Definition 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-Direktive oder ein Assemblyverweis?).

But if I call Html.RenderPartial in MyView.cshtml everything works fine.

I guess I have to change some web.configs, because the HtmlHelper in MyView is taken from System.Web.Mvc and the HtmlHelper in MyHelper.cshtml is taken from System.Web.WebPages.

How do I fix this?


回答1:


Html is a property of the WebPage, so you have access to it only inside the view. The custom helper in your App_Code folder doesn't have access to it.

So you need to pass the HtmlHelper as parameter if you need to use it inside:

@using System.Web.Mvc.Html

@helper SimpleHelper(System.Web.Mvc.HtmlHelper html, string inputFor)
{
    <span>@inputFor</span>
    html.RenderPartial("Partial");
}

and then call the custom helper by passing it the HtmlHelper instance from the view:

<html>
    <head>

    </head>
    <body>
        @WFRazorHelper.SimpleHelper(Html, "test")
    </body>
</html>


来源:https://stackoverflow.com/questions/12510840/why-i-cant-use-html-renderpartial-in-razor-helper-view-file-in-app-code-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!