Dunno if this was happening in the PR or Beta, but if I create an extension method on HtmlHelper
, it is not recognized in a Razor powered page:
namespace SomeNamespace.Extensions {
public static class HtmlExtensions {
public static string Foo(this HtmlHelper html) {
return "Foo";
}
}
}
I added it to the <Namespaces>
section in Web.config
:
<pages>
<namespaces>
<add namespace="System.Web.Mvc" />
<!-- snip -->
<add namespace="SomeNamespace.Extensions"/>
</namespaces>
</pages>
But it throws a compile error when trying to view the page:
@Html.Foo()
If I recreate the page with WebForms it works fine. What's the deal?
Workaround
If I include @using SomeNamespace.Extensions
in my Razor view, then it works, but I'd much rather just have it in Web.config
I found that putting this section in my web.config for each view folder solved it.
As the accepted answer suggests you can add "using" to all views by adding to section of config file.
But for a single view you could just use
In my case use VS 2013, and It's not support MVC 3 natively (even of you change ./Views/web.config): https://stackoverflow.com/a/28155567/1536197
Since ASP.NET MVC 3 RTM is out there is no need for config section for Razor. And these sections can be safely removed.
Since the Beta, Razor uses a different config section for globally defining namespace imports. In your
Views\Web.config
file you should add the following:Use the MVC 3 upgrade tool to automatically ensure you have the right config values.
Note that you might need to close and reopen the file for the changes to be picked up by the editor.
This error tells you that you do not have the razor engine properly associated with your project.
Solution: In the Solution Explorer window right click on your web project and select "Manage Nuget Packages..." then install "Microsoft ASP.NET Razor". This will make sure that the properly package is installed and it will add the necessary entries into your web.config file.