且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-02-24 09:29:56

您需要交换路由的顺序.我还建议您在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 }
);