现在的位置: 首页 > 综合 > 正文

asp.net mvc Global中如何注册Area

2012年09月04日 ⁄ 综合 ⁄ 共 1136字 ⁄ 字号 评论关闭

asp.net mvc 2增加Area的特性,让我们可以在每个Area之间作并行开发,而且互相并不影响。但是每次都需要在Global.asax.cs的Application_Start()方法中调用了AreaRegistration.RegisterAllAreas()方法进行注册Area的路由。我想能不能根据需要动态的注册Area,有想法就要去做,回答是可以的。

首先不需要创建继承于AreaRegistration的类,然后将每个area的route注册写到Global.asax.cs中

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


            routes.Add(new Route("Price/{controller}/{action}/{id}", new MvcRouteHandler())
            {
                Defaults = new RouteValueDictionary(new { controller = "Home", action = "Index", id = UrlParameter.Optional }),
                DataTokens = new RouteValueDictionary(new {area="Price", namespaces = new[] { "Sobey.MAM.MvcWeb.Areas.Price" } })
            });

            routes.Add(new Route("Root/{controller}/{action}/{id}", new MvcRouteHandler())
            {
                Defaults = new RouteValueDictionary(new { controller = "Home", action = "Index", id = UrlParameter.Optional }),
                DataTokens = new RouteValueDictionary(new { area = "Root", namespaces = new[] { "Sobey.MAM.MvcWeb.Areas.Root" } })
            });

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new { controller = "Login", action = "LogOn", id = UrlParameter.Optional } // Parameter defaults
            );
        }

需要注意的一点是一定要声明AreaName并保存到Route.DatattTokens中,否则不能定位到相应的area目录。

 

 

【上篇】
【下篇】

抱歉!评论已关闭.