ActionLink显示查询字符串而不是URL参数

时间:2016-07-11 04:48:03

标签: c# asp.net-mvc asp.net-mvc-routing html.actionlink

我的问题与其他问题非常相似。在MVC .Net 4.5中使用ActionLink时,我得到一个参数的查询字符串,而不仅仅是一个URL路径。我尝试了解决方案HERE,但它没有用。

CODE -

在RouteConfig.cs内部 -

  routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

  routes.MapRoute(
            name: "MyControllerRoute",
            url: "{controller}/{action}/{id}/{description}",
            defaults: new { controller = "MyController", action = "MyAction", id = UrlParameter.Optional, description = UrlParameter.Optional }
        );

Inside HomeController.cs -

public ActionResult Index(){
  --do stuff--
   return View();
}

MyController.cs内部 -

public ActionResult Vote(int id, string description){
   --do stuff--
   return View();
}

Inside Index.cshtml

@Html.ActionLink(
       "This is stuff", 
       "MyAction", 
       "MyController", 
       new { id = 123, description = "This-is-stuff"  }, 
       null)

取得这个结果 - (不是我想要的)

<a href="/MyController/MyAction/123?description=This-is-stuff">This is stuff</a>

期望的结果 - (我如何获得?)

<a href="/MyController/MyAction/123/This-is-stuff">This is stuff</a>

1 个答案:

答案 0 :(得分:1)

您需要交换路线的顺序。我还建议您在url定义中使用控制器名称(以及可选的操作名称)以防止可能与其他路由冲突。此外,只有最后一个参数可以标记为UrlParameter.Optional(否则,如果只提供了其中一个参数,则路由将被忽略,并且url将恢复为使用查询字符串值)。您的定义应该是(按顺序)

routes.MapRoute(
    name: "MyControllerRoute",
    url: "MyController/MyAction/{id}/{description}",
    defaults: new { controller = "MyController", action = "MyAction" }
);

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
相关问题