In order for a single Razor view to have a code-behind file, it must be changed to inherit from another class instead of the default view page class, which is defined in the ~/Views/web.config as
The view base class is modified with this addition to the view's markup file:
@inherits <class name>
For example, a code-behind class for ~/Views/Home/Index.cshtml would be
If you have a model specified for the view using the @model nugget you must remove it from the view code and apply it to the new base class.
Next, create a new class file for the code-behind class. Following convention, it's probably best to put the file in the same directory as the view file itself and name it similarly. I just grab the view's file name and drop the "html" from the extension. Thus, following our example, we end up with:
The generated class file needs to be modified in these ways:
- Set the base class to WebViewPage, or WebViewPage<model type> if you had a model type specified in the view code.
- Add "abstract" to the class definition (a concrete implementation of a WebViewPage derived class must implement the "Execute" method)
Continuing with our example we have a code-behind file for the Home/Index view that looks like this:
public abstract class Index : WebViewPage
// ... my super-duper code goes here
Now code away! Be sure to expose any methods you want to call from the view code as "protected" or "public" so they are visible to the view's derived class.
Just remember that a view code-behind file is not a substitute for proper separation of concerns. Remember to keep the code you place in a view code-behind class limited to only logic required to make the view do what it needs, no more. Any code that starts to smell of business/application logic should be moved to the appropriate place, either a business library or a controller.