Reputation: 2107
Not sure if I'm going about this the wrong way but I would like to have mydomain/mycontroller/myaction
return one page and mydomain/mycontroller/myaction/{id}
return a different page.
For example mydomain.com/User/Services
would return a list of services, where as mydomain.com/User/Services/2
would return just the service of the id (2 in this example).
This way the URL would appear logical to the end user, and if they so wished they could just enter an id and it would bring up the page of just that Service.
With the code below I get a non-optional parameter error if I don't make it int?
as it forgoes the named Services
ActionResult and tries to use the re-routed one.
Is this possible?
Code
Controller:
[Route("Services/{id}")]
public ActionResult Service(int? id)
{
return View();
}
public ActionResult Services()
{
return View();
}
RoutConfig:
routes.MapRoute(
name: "Service",
url: "{controller}/Services/{id}",
defaults: new { controller = "User", action = "Service", id = UrlParameter.Optional }
);
Upvotes: 0
Views: 124
Reputation: 3233
you need to define multiple routes
routes.MapRoute(name: "Services",//Service_withoutid
url: "{controller}/Services",
defaults: new
{
controller = "User",
action = "Services",
// nothing
}
);
routes.MapRoute("Service", //Service_withid
url: "{controller}/Service/{id}",
defaults: new
{
controller = "User",
action = "Service",
id = UrlParameter.Optional
}
);
Upvotes: 1