ActionLink is showing query string instead of URL parameters

倖福魔咒の 提交于 2019-12-11 06:07:22

问题


My question is very similar other questions. When using an ActionLink in MVC .Net 4.5, I am getting a query string for one parameter, instead of just a URL path. I tried the solution HERE, but it did not work.

CODE-

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

Inside 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)

GETTING THIS RESULT - (NOT WHAT I WANT)

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

DESIRED RESULT - (HOW CAN I GET THIS?)

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

回答1:


You need to swap the order of the routes. I would also recommend that you use the controller name (and optionally the action name) in the url definition to prevent possible conflicts with other routes. In addition, only the last parameter can be marked as UrlParameter.Optional (otherwise if only one of the parameters were provided, the route would be ignored and the url would revert to using query string values). Your definitions should be (in order)

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


来源:https://stackoverflow.com/questions/38299337/actionlink-is-showing-query-string-instead-of-url-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!