Using Interfaces for Model in ASP.NET MVC…

Brad Wilson tweeted asking about using interfaces for models in an ASP.NET MVC project and I was tempted to respond but figured this, rather than the 140 character limited avenue of Twitter, would be a better medium. The short answer is that we used binders and attributes to do our heavy lifting for us so that instead of our code looking like this:

public ActionResult Login(string username, string password, bool rememberMe)
{
  ...
}

it ended up looking like this:

public ActionResult Login([Model]ILoginModel model)
{
  ...
}

with the declaration of the model looking like this:

public interface ILoginModel
{
  string Username{get;set;}
  string Password{get;set;}
  bool RememberMe{get;set;}
}

Our model attribute was responsible for pulling in the values from our ViewData and then binding them using the DictionaryAdapter (probably one of the most powerful, under-documented pieces of the whole stack) from Castle.

Advantages

Doing this allowed us to keep our dealings with the models strongly typed (yes, this is NOT unique to using interfaces vs. classes), minimized the code needed for the model since it’s just an interface but also keeps anyone from “accidentally” pushing logic down into the model that belongs elsewhere.

Next up, the guts of how we used DictionaryAdapter to do this…


David O’Hara is a Principal with Improving Enterprises in Dallas, Texas.

About these ads

One Response to Using Interfaces for Model in ASP.NET MVC…

  1. […] to VoteUsing Interfaces for Model in ASP.NET MVC… (8/5/2009)Wednesday, August 05, 2009 from blog.davidohara.netBrad Wilson tweeted asking about using interfaces […]

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: