Bryse23_web
Bryse23_web

Reputation: 19

How to define razor helper for C# MVC project so that namespace is found?

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:

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?

Upvotes: 1

Views: 1781

Answers (2)

Chris Pratt
Chris Pratt

Reputation: 239430

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.

Upvotes: 3

Win
Win

Reputation: 62300

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.

Upvotes: 0

Related Questions