In a previous post I asked a question about getting started with helpers. I was successful but when I tried to use the technique 1. To write a different helper based on Html.RenderAction, and 2. To pass in my own custom helper I got errors once they were exported to App_Code.
Again, to emphasise, they work inline, but not when exported to App_Code.
Here is the original code:
Many parts of my code have only the following:
<section class="Box">
@{ Html.RenderAction("PageOne"); }
</section>
Many other parts have this:
@if (@Model.PageTwo)
{
<section class="Box">
@{ Html.RenderAction("PageTwo"); }
</section>
}
So my first step was to extract out into an inline helper the following which could be used in all of my code blocks above:
@helper Item(HtmlHelper html, string action, string htmlClass)
{
<section class="@htmlClass">
@{ html.RenderAction(action); }
</section>
}
The helper above allows me to replace all the code blocks that look like the first code segment above with this line:
@Item(Html, "PageOne", "Box")
Then I went on to write the second helper which looks like this:
@helper Item(HtmlHelper html, string action, string htmlClass, bool test)
{
if (test)
{
@Item(html, action, htmlClass)
}
}
This helper allows me to replace all the code blocks that look like the second code segment above with this line:
@Item(Html, "PageTwo", "Box", @Model.ShowThisTorF)
My main question once again is, this works inline, so why not when I remove it to App_Code.
Once I move it to App_Code I get the following errors:
The first problem is regarding adding a using reference (because HtmlHelper is ambiguous) to which I add the following line of code:
@using HtmlHelper=System.Web.Mvc.HtmlHelper
This removes the first error but then I get another error:
System.Web.Mvc.HtmlHelper does not contain a definition for
‘RenderAction’ and no extension method ‘RenderAction’ accepting a
first argument of type ‘System.Web.Mvc.HtmlHelper’ could be found (are
you missing a using directive or an assembly reference?)
I have also tried the other reference but with no result:
@using HtmlHelper=System.Web.WebPages.Html.HtmlHelper
Another problem that I am having is that I don’t think the second block will work once I get the first one working. Even though it worked fine inline.
Also, I know its obvious, but if I don’t say it here, someone will ask it in their answer. When I moved it out to the file App_Code, I did indeed add the file name prefix as required so the one line lumps of code looked something like:
@Helpers.Item(Html, "PageOne", "Box")
@Helpers.Item(Html, "PageTwo", "Box", @Model.ShowThisTorF)
Thanks for any help with this.
The correct
HtmlHelperinside helpers in the App_Code directory is theSystem.Web.Mvc.HtmlHelper.Because
RenderActionis an extension method you need to add ausingfor the namespace where it is declared which is@using System.Web.Mvc.HtmlSo this should work assuming your file is named
Helpers.cshtmland in the App_Code directory:And the usage: