[asp.net-mvc] Razor-based view doesn't see referenced assemblies

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?

This question is related to asp.net-mvc asp.net-mvc-3 razor

The answer is


In ASP.NET Core MVC the solution is to add a using in _ViewImports.cshtml, instead of putting it web.config in the View folder when working with ASP.NET MVC 5.

_ViewImports.cshtml

@using mySolution
@using mySolution.ViewModels // <-- Add this, and place your ViewModel (e.g. LoginViewModel) in here.
@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

View

@model LoginViewModel // Add to _ViewImports to make this line work
<div>This is the View for the login screen.</div>

In my case, I was using Razor Views outside of a web application.
Copying the dlls to my bin folder in solution solved the problem.


in spacename models, yourClassModel, add public before name class

public class yourClassModel{
    prop
}

include the entire namespace

@model namespace.myclasses.mymodel

In my case, the separate project that contained the namespace was a Console Application. Changing it to a Class Library fixed the problem.


I also had the same issue, but the problem was with the Target framework of the assembly.

The referenced assembly was in .NET Framework 4.6 where the project has set to .NET framework 4.5.

Hope this will help to someone who messed up with frameworks.


For me I was referencing a project that was a console application. It was set to build as an exe (console application) instead of class library (DLL). When I changed this I was able to see the models from that separate project no problem.


I was getting a similar error after moving my dev machine from Win7 32bit to Win7 64bit. Error message:

...\Web\Views\Login.cshtml: ASP.net runtime error: [A]System.Web.WebPages.Razor.Configuration.HostSection cannot be cast to [B]System.Web.WebPages.Razor.Configuration.HostSection. Type A originates from System.Web.WebPages.Razor, Version=1.0.0.0 ... Type B originates from ... Version=2.0.0.0

Turns out I had both versions in the GAC. The View web.config referenced v1 but the app was referencing v2. Removed the referenced assemblies and re-added v1. of System.Web.WebPages.Razor, etc.


You seem to be looking for this answer: https://stackoverflow.com/a/4136773/176877

That is, open the inner Views\Web.Config (NOT the root one), and add the namespace under the Pages tag:

<system.web.webPages.razor>
  <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory.../>
  <pages pageBaseType="System.Web.Mvc.WebViewPage">
    <namespaces>
      <add namespace="System.Web.Mvc" />
      ...
      <add namespace="System.Web.Routing" />
      <!-- Your namespace here -->
    </namespaces>

Save that, then close and reopen the Razor file.

If you're using Areas you'll need to do this for each Web.Config in each Area.

Visual Studio has gotten buggier over the years so it may require closing the Razor file running a Debug build then reopening the Razor file, or may in the worst require restarting Visual Studio. But ultimately it will present the Razor file to you as though everything in that namespaces list was in @using statements at the top of all your Views.


In my case the package I tried to use was referencing .net standard 2.1 while my razor class library project was set to 2.0


I was getting the same error while trying to use Smo objects in a Razor view. Apparently this is because Razor can't find the DLLs referenced in the project. I resolved this by setting "Copy Local" to true for all Smo dlls, however there might be a better solution (see Czechdude's link above) @using and web.config edits are useless because they are only needed if you wish to omit the namespace part from the type names (for instance Server instead of Microsoft.SqlServer.Management.Smo.Server)


Your Project FOLDER name needs to be the same. If your Project or Solution name is different, then MVC will hurt you.

Example : If you create a new Application and it gets the default name Webapplicaiton1, then this namespace will be created. So, let us say that you dont want to have this namespace, so from the VS you change everywhere you can see to "MyNamespace". You also search and replace all code from "Webapplication1" and replace it with "MyNamespace". This also changes web.config file, so that it inculdes

Now everything will work, except Razor views.

RazorViews cannot find it, because there is some kind of strange dependency on the FOLDERNAME of the project. It is terrible design.

I have tested this semi-thoroughly by copying my files into a new solution, and the only difference being the foldername.


well, for me it was different. I was missing assembly of my console application project with MVC project. So, adding reference was not enough.

well this might help someone else. go to root web.config file system.web -> compilation -> add your project reference like this.

<assemblies> <add assembly="Your.Namespace, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"/> </assemblies>


This solution worked for me (It's funny, but works)

I edited the view pages and copied the contents and pasted in it,i didn't change any content of the views, but just edited so the visual studio could do it's thing to track the pages, and afterwards every thing started working

Solution - Just edit the pages and replace with the same pages (Worked for me)


I had the same problem: MVC3 Project MyCore.Web was referencing to MyCore.DBLayer namespace from another project in the same solution (with assembly name MyCoreDBLayer). All objects from MyCore.DBLayer worked perfectly in Controllers and Models but failed in Razor views with an error 'The type or namespace name 'DBLayer' does not exist in the namespace 'MyCore' (are you missing an assembly reference?)' which was obviously not the case.

  • Copy Local option was set to true.
  • Adding "using..." statements in Razor views was useless
  • Adding namespaces to system.web.webPages.razor section was useless as well

Adding assembly referecene to system.web/compilation/assemblies section of the root web.config file fixed the issue. The section now looks like:

<system.web>
    <compilation debug="true" targetFramework="4.0">
      <assemblies>
        <add assembly="System.Web.Abstractions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Routing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <add assembly="System.Web.WebPages, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        **<add assembly="MyCoreDBLayer" />**
      </assemblies>
    </compilation>
...
</system.web>

Omitting version, culture, token was OK for now, but should be fixed in the future.


None of the above worked for me either;

  • Dlls were set to Copy Local
  • Adding namespaces to both web.configs did nothing
  • Adding assembly references to system.web\compilation\assemblies also did not help (although I have not removed these references, so it may be that they are needed too)

But I finally found something that worked for me:

It was because I had my Build Output going to bin\Debug\ for Debug configuration and bin\Release\ for Release configuations. As soon as I changed the Build Configuation to "bin\" for All configuations (as per image below) then everything started working as it should!!!

Build Configuration

I have no idea why separating out your builds into Release and Debug folders should cause Razor syntax to break, but it seems to be because something couldn't find the assemblies. For me the projects that were having the razor syntax issues are actually my 'razor library' projects. They are set as Application Projects however I use them as class libraries with RazorGenerator to compile my views. When I actually tried to run one of these projects directly it caused the following Configuration error:

Could not load file or assembly 'System.Web.Helpers, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.

This lead me to trying to change the Build Output, as I notice that for all web projects the Build Output seems to always be directly to the bin folder, unlike the default for class libraries, which have both release and debug folders.


None of these https://stackoverflow.com/a/7597360/808128 do work for me. Even "adding assembly referecene to system.web/compilation/assemblies section of the root web.config file". So the two ways remains for me: 1) to add a public wrap class for my assembly that Razor code can access to this assembly through this wrap; 2) just add assembly logic to a public class in the same assembly where the Razor's code is located.


In addition to making the web.config changes for <assemblies> and <namespaces>, I found that GAC'ing the assembly made a big difference. You can apply culture and public key token like any core .NET assembly that is registered globally.

Some may shudder at the mention of the GAC. But as a BizTalk developer I've grown to embrace it.


Try adding the namespace your MyClasses is in to the web.config under

<pages> <namespaces></namespaces> </pages>


Examples related to asp.net-mvc

Using Lato fonts in my css (@font-face) Better solution without exluding fields from Binding Vue.js get selected option on @change You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to send json data in POST request using C# VS 2017 Metadata file '.dll could not be found The default XML namespace of the project must be the MSBuild XML namespace How to create roles in ASP.NET Core and assign them to users? The model item passed into the dictionary is of type .. but this dictionary requires a model item of type How to use npm with ASP.NET Core

Examples related to asp.net-mvc-3

Better solution without exluding fields from Binding IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication” Can we pass model as a parameter in RedirectToAction? return error message with actionResult Why is this error, 'Sequence contains no elements', happening? Failed to load resource: the server responded with a status of 500 (Internal Server Error) in Bind function 500.19 - Internal Server Error - The requested page cannot be accessed because the related configuration data for the page is invalid String MinLength and MaxLength validation don't work (asp.net mvc) How to set the value of a hidden field from a controller in mvc How to set a CheckBox by default Checked in ASP.Net MVC

Examples related to razor

Uncaught SyntaxError: Invalid or unexpected token How to pass a value to razor variable from javascript variable? error CS0103: The name ' ' does not exist in the current context how to set radio button checked in edit mode in MVC razor view @Html.DropDownListFor how to set default value Razor MVC Populating Javascript array with Model Array How to add "required" attribute to mvc razor viewmodel text input editor How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas Multiple radio button groups in MVC 4 Razor How to hide a div element depending on Model value? MVC