Why doesn’t this work?
Route:
routes.MapRoute(
"Summary",
"{controller}/{id}",
new { controller = "Summary", action = "Default" }
);
Controller:
public class SummaryController : Controller
{
public ActionResult Default(int id)
{
Summary summary = GetSummaryById(id);
return View("Summary", summary);
}
}
URL:
http://localhost:40353/Summary/107
Error:
Server Error in '/' Application.
The resource cannot be found.
Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly.
Requested URL: /Summary/107
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.225
Update:
Let me update the question with a more intelligent one. How can I have both of these?
routes.MapRoute(
"Home",
"{controller}",
new { controller = "Home", action = "Default" }
);
routes.MapRoute(
"Summary",
"{controller}/{id}",
new { controller = "Summary", action = "Default" }
);
How do routes work (by default)?
Let’s get back to the default route, which is somewhat like this one:
Let’s try to understand how this one works.
If you access
/, it will call theIndexaction of theHomecontroller; the optional Id was ommitted.If you access
/Cit will call theIndexaction of theCcontroller; the optional Id was ommitted.If you access
/C/Ait will call theAaction of theCcontroller; the optional Id was ommitted.If you access
/C/A/1it will call theAaction of theCcontroller with id1.So, that route allows any URLs of the form
/,/C,/C/Aand/C/A/1whereCis a controller andAis an action. What does this mean? This means that you don’t necessarily have to specify your own routes.So, without routes you could just have a
HomeControllerand aSummaryControllerand add an action to that last controller calledShow.Then
/Summary/Show/1would callSummaryController.Show(1)What if I want to have a shorter route (/Controller/Id) for a controller?
Let’s suppose we do want to map routes such that
/Summary/1callsSummaryController.Show(1).Here is the correct form:
Note that we have changed the
Homeroute to look like theDefaultroute. Now we’ve added aSummaryroute where we tell that URLs of the formSummary/{id}will trigger that route. When they do, it calls theShowaction of theSummarycontroller and pass alongidas a parameter; which is exactly what you want…Also note that we need to place the
Summaryroute first such that it gets precedence.Caution: You will not want to create a new route for every single action you create. You also don’t want all your actions to be in the same controller. Consider rethinking your approach if one of these is the case, so that you don’t end up with problems later…