Are you using ASP.NET MVC? Do you want a strongly typed
ViewData.Model object without a code-behind file? Tough, who said life
was fair? I am just kidding ;p.
After reading Look Ma, No Code-Behind!
by Chad Myers, I was inspired to share my approach. In my approach, I
swap a code-behind file for an ordinary class file. I create a file
per view folder named _ViewDataModelType.cs. The file name is optional
and can be changed per view folder. I like to use the same name over
and over because I am lazy.
Setup
In this file I declare all the ViewPage and
ViewUserControl subclasses needed for this particular view folder. Use
your namespaces wisely because if you're not careful you can run into
naming collisions. Below is an example of what one these classes might
look like.
namespace NoCodeBehind.Views.Employee {
public class EmployeeIndex : ViewPage<IEnumerable<Employee>> {
}
public class EmployeeShow : ViewPage<EmployeeViewModel> {
}
public class EmployeePartial : ViewUserControl<EmployeePartialViewModel> {
}
}
Usage
All you need now is to wire up your .aspx page. The Inherits attribute is the important piece. Below is an example.
<%@ Page Language="C#" AutoEventWireup="true" Inherits="NoCodeBehind.Views.Employee.EmployeeIndex" %>
After that, you are done. You now have a strongly typed model object at your finger tips.
Conclusion
Using a code-behind file for every view page
is a non-option for me. This is a simple work around and helps keep my
project slim around the waistline. I am definitely open to other
solutions to this issue. I hope this helps if you are wrestling with
the same issue.
Tags: asp.net mvc