Why are @Scripts and @Styles commands not be recognized in MVC4 Razor layout file?

Make sure that the System.Web.Optimization.dll assembly has been referenced in your project and that the <add namespace="System.Web.Optimization"/> namespace has been added to your ~/Views/web.config file (not ~/web.config file):

<system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=4.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.Optimization"/>
        <add namespace="System.Web.Routing" />
      </namespaces>
    </pages>
</system.web.webPages.razor>

The System.Web.Optimization.dll assembly is contained within the Microsoft.AspNet.Web.Optimization NuGet, so make sure that it is installed in your project (when you create a new ASP.NET MVC 4 project in Visual Studio using the Internet Template this NuGet is automatically added to the project).


If you are using bundles (as in the example in question) you may also need to add bundle configuration to your app:

Add Bundle Config to your App_Start folder:

public class BundleConfig
{
    public static void RegisterBundles(BundleCollection bundles)
    {
        bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
            "~/Scripts/jquery-{version}.js"));

        bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
            "~/Scripts/jquery.validate.js",
            "~/Scripts/jquery.validate.unobtrusive.js"
            ));

        bundles.Add(new StyleBundle("~/Content/css").Include(
            "~/Content/YourStyles.css"));

#if DEBUG

        BundleTable.EnableOptimizations = false;
#else
        BundleTable.EnableOptimizations = true;
#endif
    }
}

Add the following line to your Global.asax.cs

BundleConfig.RegisterBundles(BundleTable.Bundles);

There are two webconfig files in your project ... both of them need to have

<add namespace="System.Web.Optimization"/>