Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 899
smunar Avatar asked Sep 20 '12 10:09

smunar


1 Answers

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>
like image 51
Darin Dimitrov Avatar answered Sep 28 '22 06:09

Darin Dimitrov