MVC 2.0 dynamic routing for category names in an e-store

北城以北 提交于 2019-12-03 14:13:37

A single route with a dynamic constraint might be a more elegant solution. Just set up a constraint that only matches your categories.

     routes.MapRoute(
        "Category",
        "{alias}/{pageNumber}",
        new { controller = "Categories", action = "Browse", alias = UrlParameter.Optional, pageNumber = 1 },
        new { alias = new CategoryMatchConstraint() } );


 public class CategoryMatchConstraint : IRouteConstraint
 {
      public bool Match( HttpContextBase httpContext,
                         Route route,
                         string parameterName,
                         RouteValueDictionary values,
                         RouteDirection routeDirection )
      {
           var category = values.Values[parameterName] as string;
           if (string.IsNullOrEmpty(category))
           {
                return false;
           }
           using (var db = new MyDatabaseContext())
           {
                return db.Categories.Any( c => c.Name == category );
           }
      }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!