您的位置:首页 > 编程语言 > ASP

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

2017-02-10 15:00 573 查看

本文参考:https://www.geek-share.com/detail/2591717300.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 = "" })

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: