8

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?

smunar
  • 195
  • 3
  • 10

1 Answers1

16

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>
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • no doesn´t work for me. First a simple syntax error because of '{' '}' after removing them I get an Error because of ambiguous reference. ['HtmlHelper' is an ambiguous reference between 'System.Web.WebPages.Html.HtmlHelper' and 'System.Web.Mvc.HtmlHelper' – smunar Sep 20 '12 at 10:54
  • You could explicitly specify the type in the function. Also notice that you should include `@using System.Web.Mvc.Html` instead of `@using System.Web.Mvc` See my updated answer. – Darin Dimitrov Sep 21 '12 at 07:20
  • i tried this too `@using mvc = System.Web.Mvc @helper SimpleHelper(string inputFor, mvc.HtmlHelper wvp){ @inputFor wvp.RenderPartial("Partial"); }` – smunar Sep 21 '12 at 07:26
  • Please see my updated answer and use the **exact code** shown there. – Darin Dimitrov Sep 21 '12 at 07:32
  • Do you know what the problem was? I already tried exactly the same code already, but I always got the same error, but I never builded it. This time I builded it although and suddenly the Warning and Error-Messages are gone. Thanks! – smunar Sep 21 '12 at 07:40