I am trying to pass parameters to the route but I am having a hard time. I want that when I type “Articles/230” in the URL it should invoke the Detail action as shown below:
public ActionResult Detail(int id)
{
return View();
}
I have the following in my Global.asax file:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Articles", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
routes.MapRoute(
"ArticleDetails", // Route name
"Articles/{id}", // URL with parameters
new { controller = "Articles", action="Detail", id = 0 } // Parameter defaults
);
}
And here is the view:
@foreach(var article in Model)
{
<div class="article_title">
@Html.ActionLink(@article.Title, "Detail", "Articles", new { id = @article.Id})
</div>
<div>
@article.Abstract
</div>
The order of routes is important because they are evaluated in the same order they are defined. So oimply invert the order:
Now when you request
Articles/123it will invoke theDetailaction on theArticlescontroller and pass123as theidparameter.