【ASP.NET MVC 学习笔记】- 09 Area的使用

本文参考:http://www.cnblogs.com/willick/p/3331519.html

1、ASP.NET MVC允许使用 Area(区域)来组织Web应用程序,这对于大的工程非常有用,每个Area代表应用程序的不同功能模块。Area 使每个功能模块都有各自的文件夹,文件夹中有自己的Controller、View和Model。

2、新建一个Area,和一个空的MVC程序一样,只是多了一个继承自AreaRegistration的类,该类如下:

    public class MyAreaAreaRegistration : AreaRegistration
    {
        public override string AreaName
        {
            get
            {
                return "MyArea";
            }
        }
        
//定义了一个默认路由,路由的名字一定要与整个应用程序的都不一样
public override void RegisterArea(AreaRegistrationContext context) { context.MapRoute( "MyArea_default", "MyArea/{controller}/{action}/{id}", new { action = "Index", id = UrlParameter.Optional } ); } }

    RegisterArea 方法不需要我们手动去调用,在 Global.asax 中的 Application_Start 方法已经有下面这样一句代码为我们做好了这件事:

protected void Application_Start() 
{
    AreaRegistration.RegisterAllAreas();

    WebApiConfig.Register(GlobalConfiguration.Configuration);
    FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    BundleConfig.RegisterBundles(BundleTable.Bundles);
}

3、如果我们现在在根目录的 Controller 文件夹中添加一个名为 Home 的 Controller,Areas文件夹下同样添加一个名为Home的Controller,然后我们通过把URL定位到 /Home/Index,路由系统无法匹配到根目录下的 Controller。这就是Controller的歧义。为了避免这种歧义,需要在RouteConfig.cs文件中定义的路由中加上对应的 namespaces 参数:

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

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
        namespaces: new[] { "MvcApplication1.Controllers" }
    );
}

4、Area生成链接:

//在Area中生成当前Area的URL链接
@Html.ActionLink("Click me", "About")

//生成指向Support这个Area的URL链接
@Html.ActionLink("Click me to go to another area", "Index", new { area = "Support" }) 

//在当前Area生成指根目录某个controller的链接,那么只要把area变量置成空字符串
@Html.ActionLink("Click me to go to top-level part", "Index", new { area = "" })

 

posted @ 2017-02-10 15:00  wangwust  阅读(150)  评论(0编辑  收藏  举报