Nov 13 2008

Strongly Typed Model Object Without Code-Behind (Sort of)

Category: Software Developmentemilioc @ 20:21

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:

Comments

1.
Angus McDonald Australia says:

I like the idea, although I'm wary of using a single file for this purpose. It both makes another place you need to go change if you want to make a change to that View's ViewData, and it can create check-out problems if you're still using VSS (but then who is any more?).

I'd prefer a solution like Chad's that involves code in the actual View file.

2.
emilioc United States says:

I agree that the one file approach violates the SRP.  Then again, creating a class file for each model type smells of lazy class.  I am eager to see the code that makes Chad's solution work.  I think ultimately, it will be a better way to solve the code-behind problem.

3.
Angus McDonald Australia says:

Yeah, I'm waiting to see a lot more of what Chad and Jeremy discussed about their OMVC framework. It makes a lot of sense and will be interesting to see in action!

Comments are closed