Asp.net-mvc – Razor-based view doesn’t see referenced assemblies

asp.net-mvcasp.net-mvc-3razor

I'm attempting to create a strongly-typed view based on a class from another assembly. For whatever reason though, my Razor view doesn't seem to have any visibility of other assemblies referenced on my project. e.g.

@model MyClasses.MyModel

results in the error in Visual Studio 2010, "The type or namespace name MyClasses could not be found (are you missing a using directive or an assembly reference?)."

The same class referenced in the standard view engine works fine. I have the same trouble trying to reference the class in the body of my view.

Am I missing something about Razor or do I need to reference the assembly some other way?

Best Answer

There is a new configuration section that is used to reference namespaces for Razor views.

Open the web.config file in your Views folder, and make sure it has the following:

<configuration>
    <configSections>
        <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
            <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
            <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
        </sectionGroup>
    </configSections>

    <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="SquishIt.Framework" />
                <add namespace="Your.Namespace.Etc" />
            </namespaces>
        </pages>
    </system.web.webPages.razor>
</configuration>

Alternatively, you can add using statements to your shared layout:

@using Your.Namespace.Etc;
<!DOCTYPE html>
<head>
....

After editing the Web.config, restart Visual Studio to apply the changes.

Related Topic