Is there some sort of magic I need to use to get the namespaces in the pages/namespaces
element in the webconfig?
<pages>
<namespaces>
<add namespace="System.Web.Mvc"/>
<add namespace="System.Web.Mvc.Ajax"/>
<add namespace="System.Web.Mvc.Html"/>
<add namespace="System.Web.Routing"/>
<add namespace="System.Web.WebPages"/>
<add namespace="System.Web.Helpers"/>
<add namespace="MyCustomHelpers"/>
</namespaces>
</pages>
The above just doesn't want to work. I know the namespace is fine because when I put the @using MyCustomHelpers
at the top of the page it magically works.
This is so that I can get the Html.SomeFunction()
to work without having to put @using
at the top of all my pages
If you put your namespace declaration in the
Web.config
in the root "Views" folder and/or the current area's "Views" folder (depending on where your view is) - it should work as expected.I found this http://weblogs.asp.net/mikaelsoderstrom/archive/2010/07/30/add-namespaces-with-razor.aspx which explains how to add a custom namespace to all your razor pages.
Basically you can make this
and put the following code in your AssemblyInfo.cs
the method InitializeApplication will be executed before Application_Start in global.asax
Try closing and reopening the view after making sure the changes were made to the web.config in the root of view.
Closing and Reopening fixed my problem.
See here:
ASP.NET MVC 4 namespace issue in razor view
For what it's worth, another technique is to simply put your helper extension class in a System namespace that is already included by the view engine by default. For example:
This way, as long as the library containing the class is referenced, everything will see it. Since you are extending a
System.Web.Mvc
class, it seems reasonably acceptable to put the extension methods in the same namespace.Update: please take a look at my updated answer that applies to MVC 3 RC: Razor HtmlHelper Extensions (or other namespaces for views) Not Found
This has changed between MVC 3 Preview 1 and MVC 3 Beta (released just today). In Preview 1 Razor used the WebForms namespaces config section. However in the Beta there is a new config section that is seperate from the WebForms one. You will need to add the follwing to your web.config file (or just start with a brand new project from the template):
Note that you might need to close and reopen the file for the changes to be picked up by the editor.
Note that there are other changes to what is required in web.config to get Razor to work in MVC3 Beta so you would be best off to take a look at the
~\View\Web.config
file that ships in the Beta project templates.