zoukankan      html  css  js  c++  java
  • 【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 = "" })
  • 相关阅读:
    根据实体中一个属性值查找实体数组中的所有实体并放到list中
    asp.net ajax 客户端框架未能加载 sys 未定义
    SYS_CONNECT_BY_PATH函数用法 ORACLE
    滚动条小结 平时容易忘记的小东西 JAVASCRIPT
    ORACLE 和 SQL 分别实现递归的方法
    JS 获取控件的绝对位置
    GridView内控件获取所在行的信息
    sql server 使用for xml path 将1列多行转换为字符串连接起来
    ORACLE 行转列 及函数定义
    子窗口刷新父窗口 javascript 并调用父窗口函数
  • 原文地址:https://www.cnblogs.com/wangwust/p/6386660.html
Copyright © 2011-2022 走看看