I tried adding namespaces to configuration/system.web/pages/namespaces
in the web.config of my ASP.NET MVC 3 application so I could use classes in those namespaces in my views without needing a @using, however this has no effect. How can I add namespaces to my views?
There are two ways to add namespaces: Put @using namespace at the top of the page. Put all the namespaces in Views\Web. config.
The namespace for Razor Engine is System. The Razor file extension is "cshtml" for the C# language. By default, Razor View Engine encodes html tags or scripts before it's being rendered to view that avoids Cross-Site Scripting attacks.
Mvc namespace contains classes and interfaces that support the ASP.NET Model View Controller (MVC) framework for creating Web applications. This namespace includes classes that represent controllers, controller factories, action results, views, partial view, model binders, and much more.
MVC razor has a different area for namespaces.
Look in the second web.config, the one in your Views folder and add namespaces this way.
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<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="Telerik.Web.Mvc.UI;"/>
</namespaces>
</pages>
</system.web.webPages.razor>
I'm not sure why it's so flaky, but chances are that it is actually working, but Visual Studio doesn't recognize it until you close and re-open the view you're in. Also make sure you're in the web.config that's located in the Views directory.
I used this method to include Resource files into my views but Razor didn't want to pick up my classes. After some hair-pulling I realized I didn't change the Access Modifier on the Resources.resx
file to public (it's created as Internal by default). Once I changed it & recompiled, I could access my resources from all views.
Rookie mistake, hate to see it happen, but hopefully it'll save someone some pain.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With