MVC项目在实际开发过程中,随着项目规模的扩大,Controller会随之增多,不易维护,MVC框架提供了Areas机制来分离ASP.NET MVC项目

创建Areas

Web应用通常会有前台(面向用户)和后台(面向管理员)两部分,我们希望以/locahost/Admin开始的URL都为后台管理地址,使用Areas这个功能来进行分离。

新建一个项目”MyMvcAreasDemo”,然后在项目上右键->添加->Areas,输入”Admin”,MVC会在项目根目录自动创建Areas文件夹,在Areas文件夹下会自动创建Admin文件夹,在Admin文件夹下会自动创建Controllers,Models,Views文件夹和AdminAreaRegistration.cs文件,该文件用来注册该区域的路由配置。

为了防止区域间Controller重名冲突,需要修改一下AdminAreaRegistration.cs和Global.asax,分别为路由加上命名空间限制:

/Areas/Admin/AdminAreaRegistration.cs

context.MapRoute(
    "Admin_default",
    "Admin/{controller}/{action}/{id}",
    new { action = "Index", id = UrlParameter.Optional },
    new string[] { "MyMvcAreasDemo.Areas.Admin.Controllers" }
);

/Global.asax.cs

routes.MapRoute(
    "Default",
    "{controller}/{action}/{id}",
    new { controller = "Home", action = "Index", id = UrlParameter.Optional },
    new string[] { "MyMvcAreasDemo.Controllers" }
);

此后,面向管理员的Controller就可以在Admin区域下创建

调用Areas下的Controller

Controller层面:

return RedirectToAction("action", "controller", new { area = "area-name" });

View层面:

Html.ActionLink("display-value", "action", "controller", new { area = "area-name" }, null)

Routing层面:

routes.MapRoute(
    "Default",
    "{controller}/{action}",
    new { area = "area-name", controller = "", action = "" }
    );

调用根目录下的Controller

Controller层面:

return RedirectToAction("action", "controller", new { area = "" });

View层面:

Html.ActionLink("display-value", "action", "controller", new { area = "" }, null)

Routing层面:

routes.MapRoute(
    "Default",
    "{controller}/{action}",
    new { area = "", controller = "", action = "" }
    );