Friday, September 28, 2012

Database Lookup on Route in .NET MVC4

I started messing around in .NET MVC4's Routing and was wondering if you had a custom route where you need to look up something in the database, how would that work?

I found out this was possible using the constraints attribute when you setup your route. I created a new constraint by extending IRouteConstraint and forwarded the look up on to a model where I did the database look up.

App_Start >> RouteConfig
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using myApp.App_Start;

namespace myApp
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "LocationSite",
                url: "{id}/{action}",
                defaults: new { controller = "Snowboard", action = "Index", id = UrlParameter.Optional },
                constraints: new { id = new SnowboardSiteRouteConstraint()  }/*---database lookup for snowboards---*/
            );
         }
    }
}


App_Start >> SnowboardSiteRouteConstraint
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Routing;
using myApp.Models;

namespace myApp.App_Start
{
    public class SnowboardSiteRouteConstraint: IRouteConstraint
    {
        public bool Match(HttpContextBase httpContext, Route route, string parameterName,RouteValueDictionary values, RouteDirection routeDirection)
        {
           /*---database lookup for snowboards---*/

            return SnowboardSite.IsSnowboardSiteName((string)values["id"]);

        }
    }
}


Model >> SnowboardSite
using System;
using System.Collections.Generic;
using System.Web;
using myApp.Persistence;
using myApp.Entities;
using NHibernate;
using NHibernate.Linq;

namespace myApp.Models{
    public class SnowboardSite{
        public static bool IsSnowboardSiteName(string boardName){

            /*---database lookup for snowboards, return the result as boolean---*/

            return [[result of database lookup goes here as a boolean]];
        }
    }
}

No comments:

Post a Comment