Reputation: 873
First of all, I read this question and this question I think I have another problem. Because everything is the same.
I have MVC5 project. I have 2 areas. First, my default root class like this.
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Welcome", action = "Index", id = UrlParameter.Optional});
}
first area route config.
public override void RegisterArea(AreaRegistrationContext context)
{
context.MapRoute(
"App_default",
"App/{controller}/{action}/{id}",
new { action = "Index", id = UrlParameter.Optional }
);
}
At this point, there is no problem. But I want like this:
This App/Controller
public class AccountsController : Controller
{
// GET: App/Accounts
[Route("app/accounts/list/{Id}")]
public ActionResult List()
{
return View();
}
}
Now, I can access like :
How can I route attribute using Areas? I cannot do it?
Upvotes: 1
Views: 1410
Reputation: 247088
First you need to enable attribute routing
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
//Enable attribute routing
routes.MapMvcAttributeRoutes();
//Area registration should be done after
//attribute routes to avoid route conflicts
AreaRegistration.RegisterAllAreas();
//convention-based routing
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Welcome", action = "Index", id = UrlParameter.Optional}
);
}
And then add the proper attributes to the controller
[RouteArea("AreaName", AreaPrefix = "app/accounts")]
public class AccountsController : Controller {
[HttpGet]
[Route("list/{id:int}")] // Matches GET app/accounts/list/45646
public ActionResult List(int id) {
return View();
}
}
Upvotes: 1
Reputation: 11
You need to receive an integer as a parameter in the List ActionResult in order for 'localhost/app/accounts/list/45646' URL to work.
public class AccountsController : Controller
{
// GET: App/Accounts
[Route("app/accounts/list/{Id}")]
public ActionResult List(int Id)
{
return View();
}
}
Upvotes: 1