1
votes

MVC4, Entity Framework 5, ASP.Net 4. I am trying to make a razor helper to use across multiple Areas. This has been asked a few times, but after implementing all the solutions on Google, the problem persists.

The intellisense is recognizing the helper, but on the live server I cannot escape the compile error "The type or namespace name 'MyHelpers' could not be found (are you missing a using directive or an assembly reference?)".

Here is what I have done:

  • Defined @helper class in /App_Code
  • Defined @helper class in /Views/Helpers
  • Added reference to MyHelper namespace in
    <system.web.webPages.razor> of Views/web.config
  • Added reference to MyHelper namespace in &ltsystem.web.webPages.razor> of MyArea/Views/web.config
  • Added all recommended using directives to top of Helper definition
    • @using System.Web.Mvc;
    • @using System.Web.Mvc.Html;
    • @using System.Web.Mvc.Razor;
    • @using System.Text.RegularExpressions

After every step, clean, build, restart visual studio, and re-published. But the helper namespace is still not recognized in the Razor compiler.

Does anyone have any ideas?

2

2 Answers

2
votes

Don't use view helpers (the @helper syntax). These are only evaluated at runtime and are difficult if not impossible to test properly.

Instead, create a static class that extends HtmlHelper like so:

public static class HtmlHelperExtensions
{
    public static IHtmlString Sample(this HtmlHelper htmlHelper)
    {
        ...
    }
}

If you leave off the namespace declaration, it becomes global and you can reference it from anywhere, including views. This is a bad idea with most things, but for extensions it's fine, unless you run into issues with using libraries that offer similar extensions with the same method names. If you choose to namespace them to be safe, then you just need to add the namespaces to your view directory's Web.config as you've done similarly before.

0
votes

I personally do not like adding classes inside App_Code folder which is designed for Website Project in old days.

If your solution contains just a single MVC project, you can just create a folder called Helpers inside MVC project, and place helpers classes inside it.

FYI: If you are developing a large application, you want to consider creating a separate Class Library Project for helper classes.