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

Asp.net MVC23 使用Areas功能的常见错误

2015-10-09 12:02 549 查看
一般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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: