Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding namespaces to ASP.NET MVC 3 views

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?

like image 301
Jake Petroules Avatar asked Jun 03 '11 01:06

Jake Petroules


People also ask

How do you add a namespace to a view?

There are two ways to add namespaces: Put @using namespace at the top of the page. Put all the namespaces in Views\Web. config.

Which namespace is used for razor view?

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.

Which namespace is used for ASP NET MVC?

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.


3 Answers

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>
like image 90
Rich Bianco Avatar answered Oct 22 '22 09:10

Rich Bianco


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.

like image 9
ataddeini Avatar answered Oct 22 '22 10:10

ataddeini


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.

like image 1
Carl Heinrich Hancke Avatar answered Oct 22 '22 08:10

Carl Heinrich Hancke