MVC 3 Area route not working

前端 未结 8 730
有刺的猬
有刺的猬 2020-12-17 18:54

I created a Area in my MVC 3 application called \'Blog\'.

In global.asax I have the following code.

public static void RegisterRoutes(RouteCollection         


        
8条回答
  •  囚心锁ツ
    2020-12-17 19:12

    I found what I consider to be a bug in the framework, with a workaround. If you are trying to map a default route to an MVC 3 app with areas, your global.asax file might have something like this:

    VB:

    routes.MapRoute(
          "Default",
          "{area}/{controller}/{action}/{id}",
          New With {.area = "MyArea", .controller = "Home", .action = "Index", .id = UrlParameter.Optional}
    )
    

    C#:

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

    If you go to your app root in the URL, you may get a runtime error like this:

    The view 'Index' or its master was not found or no view engine supports the searched locations. The following locations were searched:

    For some reason, the view engine does not appear to look in the area folder for the view file the same as if you type in the whole link. The strange thing is the code reaches the controller action. Here is the fix: Put this code in your controller action:

    VB:

    If Not Me.ControllerContext.RouteData.DataTokens.ContainsKey("area") Then
                    Me.ControllerContext.RouteData.DataTokens.Add("area", "MyArea")
                End If
    

    C#

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

提交回复
热议问题