简体   繁体   English

如何在MVC3中对区域使用MapRoute

[英]How to use MapRoute with Areas in MVC3

I've got an Area in my web app called "Admin". 我的网络应用程序中有一个名为“管理员”的区域。

So, http://localhost.com/Admin goes to the Home Controller and Index Action in the Admin Area. 因此, http://localhost.com/Admin转到“管理”区域中的“主控制器和索引操作”。

However, I want to be able to hit the Admin Home Controller and Index Action with the following Url: 但是,我希望能够使用以下网址访问“管理员主页控制器和索引操作”:

http://localhost.com/Hello http://localhost.com/你好

I've got this as my attempt: 我有这个作为我的尝试:

routes.MapRoute(
            "HelloPage",
            "Hello/{controller}/{action}",
            new{area= "Admin", controller = "Home", action = "Index"},
            new[] { typeof(Areas.Admin.Controllers.HomeController).Namespace });

As you can see I'm specifying the namespace and the area, but all I get is the routing error: 如您所见,我正在指定名称空间和区域,但我得到的只是路由错误:

The view 'Index' or its master was not found or no view engine supports the searched locations. 找不到视图“索引”或其主视图,或者没有视图引擎支持搜索到的位置。

It's not searching in the Admin area. 它不在“管理”区域中搜索。

Any ideas? 有任何想法吗?

Try this: 尝试这个:

routes.MapRoute(
       "HelloPage",
       "Hello/{controller}/{action}/{id}",
       new { area = "Admin", controller = "Home", action = "Index", id = UrlParameter.Optional }
);

And then add this to your Admin controller action: 然后将其添加到您的管理控制器操作中:

  if (!this.ControllerContext.RouteData.DataTokens.ContainsKey("area"))
  {
      this.ControllerContext.RouteData.DataTokens.Add("area", "Admin")
  }

You can check here for further documentation. 您可以在此处查看更多文档。

The problem was that I was setting the route in Global.asax. 问题是我在Global.asax中设置了路由。

I should have been setting it in the AreaRegistration in the Admin area. 我应该已经在Admin区域的AreaRegistration中进行了设置。 Once I did that the problem was fixed. 一旦我做了,问题就解决了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM