Please help me to correct my ASP.NET MVC Route Map.
I've got a menu item with an ActionLink:
<li>@Html.ActionLink("Articles", "List", "Article")</li>
On the Home page it looks like:
localhost/Article
which is OK.
But on the concrete Article page with URL localhost/Article/List/11
my menu link is the same:
localhost/Article/List/11
But I need localhost/Article
My route map code is as follows:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Article",
url: "Article/{action}/{id}",
defaults: new { controller = "Article", action = "List", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
Here is controller code:
public ActionResult List(int? id)
{
ArticlesDataManager artMgr = new ArticlesDataManager();
ArticleViewModel art = new ArticleViewModel();
art.Articles = artMgr.GetLastArticles();
art.Article = (id == null) ? artMgr.GetLast() : artMgr.GetArticle((int)id);
ViewData.Model = art;
return View();
}
my problem was solved by changing my route map:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "ArticleByFirst",
url: "Article/{action}/",
defaults: new { controller = "Article", action = "List" }
);
routes.MapRoute(
name: "ArticleById",
url: "Article/List/{id}",
defaults: new { controller = "Article", action = "List", id = UrlParameter.Optional }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
And my menu-link looks like: <li><a href="@Url.RouteUrl("ArticleByFirst", new { action = "List" })">Articles</a></li>
And my item-link is: <li><a href="@Url.RouteUrl("ArticleById", new { id = item.Id })">@item.Name</a></li>
It's not good, that I can't choose name of Route Map in ActionLink.