zoukankan      html  css  js  c++  java
  • ASP.NET MVC 使用Areas功能的常见错误

    一般WEB项目都会不同的页面区域,如:用户前台、用户后台、管理员后台。

    访问的URL:

    用户前台:www.domain.com/home/index

    用户后台:www.domain.com/admin/home/index

    管理员后台:www.domain.com/manager/home/index

    asp.net mvc 2/3 提供了Areas功能来实现

    1.打开新建项找到Areas,分别添加admin,manager,添加好后项目结构类似下面

    Areas下有各自独立的Controllers,Models,Views。此外还多了个文件AreaRegistration为后缀的.cs文件. 这个文件主要的作用是给Areas下的子模块配置路由。在全局文件Global.asax中的Application_Start事件里有这么一句代码 AreaRegistration.RegisterAllAreas()

    按上面的需要实现的URL建立好相应的Controllers,Views(home/index)访问URL遇到第一个问题.

    第一个问题:

    找到了多个与名为“Home”的控制器匹配的类型。如果为此请求(“{controller}/{action}/{id}”)提供服务的路由没有指定命名空间来搜索匹配此请求的控制器,则会发生此情况。如果是这样,请通过调用采用“namespaces”参数的“MapRoute”方法的重载来注册此路由

    解决方法:

    修改AdminAreaRegistration.cs 和 MarengerAreaRegistration.cs 中的路由设置,将其控制器的命名空间传入给系统,以修改 AdminAreaRegistration.cs 为,另外如果将默认的用户前台WebSite也放入Areas可以//RegisterRoutes(RouteTable.Routes);

    例子:

    public override void RegisterArea(AreaRegistrationContext context)
    {
       //直接将命名空间传入
      context.MapRoute(
        "Admin_default",
        "Admin/{controller}/{action}/{id}",
        new { controller = "Home", action = "Index", id = UrlParameter.Optional },
           new string[] { "Demo.Areas.Admin.Controllers" } //<span>controllers的命名空间</span>
      );
     
    }
    public override void RegisterArea(AreaRegistrationContext context)
    {
       //直接将命名空间传入
      context.MapRoute(
        "WebSite_default",
        "{controller}/{action}/{id}",
        new { controller = "Home", action = "Index", id = UrlParameter.Optional },
           new string[] { "Demo.Areas.WebSite.Controllers" } //controllers的命名空间
      );
     
    }

    第二个问题: 

    @Html.ActionLink对于区域Areas的设置,为了避免在admin/home/index下访问about/index出现admin/about/index about上要new{area=""}

    @Html.ActionLink("Link Text", "Action", "Controller", new { Area="<span>AreaName</span>" }, null)
    <ul id="menu">
        <li>@Html.ActionLink("Home", "Index", "Home", new { area = ""}, null)</li>
        <li>@Html.ActionLink("Admin", "Index", "Home", new { area = "Admin" }, null)</li>
        <li>@Html.ActionLink("About", "About", "Home", new { area = ""}, null)</li>
    </ul>

      

  • 相关阅读:
    使用TransactionScope实现多数据库连接事务操作
    zabbix_agentlinux下的安装
    (转)Zabbix AgentWindows平台配置指导
    使用SpringSide 3.1.4.3开发Web项目的全过程(上)
    应用开发中数据字典项设计实现方案
    Oracle Top N 和 Oracle中的limit问题解决方案
    Struts 2.0的codebehinde插件应用简述
    PropertyUtils和MethodUtils使用
    Log4j基本使用方法
    Quartz从入门到进阶
  • 原文地址:https://www.cnblogs.com/haiyabtx/p/2832798.html
Copyright © 2011-2022 走看看