ASP.NET MVC `Html.ActionLink` between “Areas”

后端 未结 6 543
灰色年华
灰色年华 2021-01-31 01:58

I have added a new Area to my MVC3 project and I am trying to link from the _Layout page to the new Area. I have added an Area called \'Admin\' that has a controller \'Meets\'.<

6条回答
  •  清歌不尽
    2021-01-31 02:38

    I solved this problem by doing the following.

    In my Global.asax.cs, I have

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }
    
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.IgnoreRoute("{*favicon}", new { favicon = @"(.*/)?favicon.ico(/.*)?" });
        }
    
        protected void Application_Start()
        {
            //Initialise IoC
            IoC.Initialise();
    
            AreaRegistration.RegisterAllAreas();
            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);
        }
    

    In my PublicAreaRegistration.cs (Public Area), I've got

    public class PublicAreaRegistration : AreaRegistration
    {
        public override string AreaName
        {
            get
            {
                return "Public";
            }
        }
    
        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute("Root", "", new { controller = "Home", action = "Index" });
    
            context.MapRoute(
                "Public_default",
                "Public/{controller}/{action}/{id}",
                new { controller = "Home", action = "Index", id = UrlParameter.Optional }
                , new[] { ".Areas.Public.Controllers" }
            );
        }
    }
    

    In my AuthAreaRegistration.cs (Area for Restricted access), I've got

    public class AuthAreaRegistration : AreaRegistration
    {
        public override string AreaName
        {
            get
            {
                return "Auth";
            }
        }
    
        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "Auth_default",
                "Auth/{controller}/{action}/{id}",
                new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
    

    And finally, my links in my *.cshtml pages would be like

    1) @Html.ActionLink("Log Off", "LogOff", new{area= "Public", controller="Home"})

    or

    2) @Html.ActionLink("Admin Area", "Index", new {area= "Auth", controller="Home"})

    Hope this saves someone hours of research! BTW, I'm talking about MVC3 here.

    Kwex.

提交回复
热议问题