ActionLink显示查询字符串而不是URL参数 [英] ActionLink is showing query string instead of URL parameters

查看:88
本文介绍了ActionLink显示查询字符串而不是URL参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

代码-

内部RouteConfig.cs-

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

内部HomeController.cs-

Inside HomeController.cs -

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

在MyController.cs内部-

Inside MyController.cs -

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

Inside Index.cshtml

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>

推荐答案

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

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

这篇关于ActionLink显示查询字符串而不是URL参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆