ASP.NET MVC路由映射

时间:2013-03-22 17:39:42

标签: asp.net-mvc asp.net-mvc-routing maproute ignoreroute

请帮我纠正我的ASP.NET MVC路线图。

我有一个带有ActionLink的菜单项:
<li>@Html.ActionLink("Articles", "List", "Article")</li>

在主页上,它看起来像: localhost/Article这没关系。

但是在具有网址localhost/Article/List/11的具体文章页面上,我的菜单链接是相同的: localhost/Article/List/11

但我需要localhost/Article

我的路线图代码如下:

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 }
    );
}

这是控制器代码:

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();
    }

2 个答案:

答案 0 :(得分:1)

通过更改我的路线图解决了我的问题:

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 }
            );
        }

我的菜单链接如下:<li><a href="@Url.RouteUrl("ArticleByFirst", new { action = "List" })">Articles</a></li>

我的项目链接是:<li><a href="@Url.RouteUrl("ArticleById", new { id = item.Id })">@item.Name</a></li>

这不好,我不能在ActionLink中选择路线图的名称。

答案 1 :(得分:0)

我猜您当前的查询字符串项目已添加到您的操作链接中。要避免此问题,请使用this重载并尝试将null显式传递为RouteValues,并查看它带来的更改。

public static MvcHtmlString ActionLink(
    this HtmlHelper htmlHelper,
    string linkText,
    string actionName,
    string controllerName,
    RouteValueDictionary routeValues,
    IDictionary<string, Object> htmlAttributes
)

所以你的代码可以重写为

<li>@Html.ActionLink("Articles", "List", "Article",
                                        new RouteValueDictionary { },null)</li>

您也可以尝试此版本

<a href="Url.Action("List", "Articles")">Articles</a>