简体   繁体   中英

Call ActionResult in the Area controller from a shared view

From the Layout.cshtml which is inside the Views folder (outside Areas), I need to resolve the action method of a controller created inside an Area.

I have a few custom routes defined, but the default route is as always:

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

Eg:

Area - Test , Controller - HomeController , Action Method - Index

@Url.Action("Index", "Home", new { Area = "Test" }) returns an empty string. @Html.ActionLink("Test link", "Index", "Home") returns an empty string.

@Html.RouteLink("Test Link", "default", new { controller = "Home", action = "Index" }) returns in an error

A route named 'default' could not be found in the route collection.

Just to clarify, this action doesn't need to be invoked using a custom route. It will never be directly accessible via a URL, so the default route should do fine.

I am bummed. How can I resolve the action?

Under the same namespace add following class

public class TestAreaRegistration : AreaRegistration
{
    public override string AreaName
    {
        get
        {
            return "Test";
        }
    }

    public override void RegisterArea(AreaRegistrationContext context)
    {
        context.MapRoute(
            "Test_default",
            "Test/{controller}/{action}/{id}",
            new { action = "Index", id = UrlParameter.Optional }
        );
    }
}

Under Global.asax make sure to have RegisterAllAreas()

protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();            
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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