<< back to blog

Really Easy Way To Partition an ASP.NET MVC With An Admin Area

.net ~ asp.net ~ mvc

26 Nov, 2009

Create ASP.NET MVC Admin Area For Your App In 10 LOC

Like most people, I'm looking forward to the addition of Areas in ASP.NET MVC 2. The main reason is so I can neatly put my admin area in a group like this example:


Until V2 is released, MVC doesn't have a default way of having this grouping of controllers. I wanted a simple 1-minute way of achieving this in MVC 1. The best way I could figure out is this:

  1. Add these 9 lines of code to your app

    public class AdminRouteHandler : IRouteHandler
        public IHttpHandler GetHttpHandler(RequestContext requestContext)
            RouteData routeData = requestContext.RouteData;
            routeData.Values["controller"] = "Admin" + requestContext.RouteData.GetRequiredString("controller");
            return new MvcHandler(requestContext);
  2. Add a new route in your Global.asax.cs

        "AdminRoutes", // Route name
        new Route(
            "Admin/{controller}/{action}/{id}", // URL with parameters
            new RouteValueDictionary(new { controller="Video", action = "Index", id=""}),
            new AdminRouteHandler()) // Parameter defaults

Tada! You're done! There's one catch...

Controllers in the Admin area must start with the "Admin" prefix.

File Names Start With Admin

You then create appropriate folders for views as usual.

View folders work as usual

This is a bit of a hack, but I like the fact that it requires very little code and it's very simple :) Also, it would be very easy to tweak this code to allow for general partitioning of controllers by prefix, so you could have a "Admin" area, a "Mobile" area etc.

P.S: If you want a more complex solution that doesn't require you to use my controller naming convention, try this one.

You may also like...
.NET Gem Fun
Running FubuMVC on Mono (OSX)
Really Easy Way To Partition an ASP.NET MVC With An Admin Area
Automating .NET development (and NHibernate) with IronRuby + Rake
Get a Rails-Stylee Interactive Shell For Your NHibernate Backed Domain Model
In Memory SQLite Testing with NHibernate
NHibernate Trick
OSX MonoDevelop MVC?
NHibernate: Calling Update Unnecessarily
.NET Config for Multiple Developers

kick it on DotNetKicks.com
blog comments powered by Disqus