I am unable to keep both routing rules working using
Url.Action("action", "Controller")
without adding new { Area = "" }
in the link.
Is this possible? Please help.
-> Yes, It is possible.We can using area in the route values wen generating URLs using 'Url.Action'
-> Define Default Route in your RouteConfig.cs file :-
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
-> Define Area-specific Routes :- Define routes for each area in the AreaRegistration class for the area, for example :-
public class MyAreaRegistration : AreaRegistration
{
public override string AreaName
{
get
{
return "MyArea";
}
}
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
name: "MyArea_default",
url: "MyArea/{controller}/{action}/{id}",
defaults: new { action = "Index", id = UrlParameter.Optional }
);
}
}
-> Generate URL without Specifiying Area :- Now, when you use Url.Action to generate URLs for controller/action within the default area.and this will generate URL :- /Home/Index
<a href="@Url.Action("Index", "Home")">Home</a>
-> Generate URL for Actio in area :- To generate Ul for action within area that time specify the area name.and URL :- /MyArea/SomeController/Index
<a href="@Url.Action("Index", "SomeController", new { area = "MyArea" })">Some Action</a>
-> follow this code, you can maintain routing for both default and area-specific controllers/actions without need to specify the area explicitly when generating URLs for default controllers/actions.