Thursday, May 23, 2013

MVC 4.0 Project Error: @Scirpts does not exist


MVC 4 enables the use of much anticipated Razor View engine. This is great, however, in my first trial run of MVC 4 in Visual Studio 2012, I faced a run-time error regarding @Scripts helper as shown below:
 

 
After some digging, it turned out that this helper is implemented in Microsoft.Web.Optimization assembly.  Don’t try to add a reference to this assembly to your project. It is unlikely that you don't find it the list of the .Net assemblies although it is sitting somewhere on your computer. The neater and cleaner approach is to click the Visual Studio “Package Manager Console” menu (Tools --> Library Package Manager).

 

The “Console” opens up in the lower pane of the Visual Studio UI displaying a PM> prompt.  We will have to use this console to install Microsoft.Web.Optimization package.  Type in the following command:
Install-Package  -id Microsoft.Web.Optimization –InstallPrerelease
 



Now it is time to tell your project to include this assembly and use it to access the @Scripts helper. This is done in the Web.Config just by adding the new namespace as follows:
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <namespaces>
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <dd namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.Optimization"/>
      </namespaces>
    </pages>
These two steps will get your issue resolved and makes the run-time happy.
Aside: The Package Manager Command Prompt is really a cut-down version of PowerShell integrated with the Visual Studio UI. You can test this by typing simple PowerShell commands such as “get-help”, “host” and see this for yourself. Specifically run the “get-help Install-Package” to get the command line syntax for Install-Package as you need to use it in this process. So you don’t need to memorize the command, instead you can as always, rely on PowerShell’s get-help command to come to the “rescue”.
Also browse through other available sub-menus in the “Library Package Manager”. There are a great deal of stuffs to learn and use. I especially liked the “Package Visualizer” and the “Package Manager Settings”.