Search code examples
c#asp.net-mvc-4app-code

Mvc4 App_Code class not visible to _Layout.cshtml


I've made a mvc4 project. It's a standard internet project made by Visual Studio Express 2012 for Web. And in there I've added a folder called App_Code, and inside that I made a class called SessionHandler.cs. Then I open the pre-made file _Layout.cshtml found in /views/shared/_Layout.cshtml. In there I try calling the class SessionHandler.cs which I made, but it doesn't seem to be able to find the class.

How can I make the SessionHandler.cs class visible to _Layout.cshtml?


EDIT:

Just adding some more info on my project:

The structure:

enter image description here

The SessionHandler.cs file

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace TestingGround01.App_Code
{
    public class SessionHandler
    {
    }
}

Solution

  • In the Web.config file located inside of your Views folder, place a namespace inclusion.

    <pages>
      <namespaces>
        <add namespace="TestingGround01.App_Code">
      </namespaces>
    </pages>
    

    To clarify, this is useful for EXTERNAL references. In your case, if you simply stick a

    @using TestingGround01.App_Code
    

    at the top of your _layout.cshmtl file, it should resolve the reference just fine.

    Then, you can instantiate your class inside your _layout.

    @{ var s = new SessionHandler(); }