使用asp-route设置参数的GET表单提交时查询参数丢失如何解决?
问题根因
使用method="get"提交HTML表单时,浏览器默认会丢弃form标签action属性中自带的查询参数,转而将表单内部所有带有name属性的可提交控件的值拼接为新的查询字符串附加到请求地址后。你的表单内只有提交按钮,没有其他带name的输入控件,因此提交后请求地址只有空的查询参数后缀。
解决方案
- 方案1:使用隐藏input传递参数(兼容性最好,也是你已经验证可行的方案)
把需要传递的参数全部以隐藏输入框的形式放入表单内,无需再在form标签上声明asp-route-*参数:
<form id="next" method="get" asp-controller="Search" asp-action="Cities"> <input type="hidden" name="sortOrder" value="@ViewData["CurrentSort"]" /> <input type="hidden" name="currentFilter" value="@ViewData["CurrentFilter"]" /> <input type="hidden" name="pageNumber" value="@(Model.PageIndex + 1)" /> <input type="submit" class="page-btn" disabled="@nextDisabled" value="Next" /> </form>
- 方案2:改用POST提交
如果不需要参数暴露在URL中,可以将表单method改为post,同时给控制器Action添加[HttpPost]注解,POST提交不会覆盖action自带的路由参数:
[HttpPost] [Route("Search/Cities")] public ActionResult Cities(string SearchString, string sortOrder, string currentFilter, int? pageNumber)
- 方案3:改用超链接模拟按钮
如果表单没有其他需要用户输入的动态内容,直接用a标签生成带参数的跳转链接更简洁,调整样式匹配按钮即可:
<a asp-controller="Search" asp-action="Cities" asp-route-sortOrder="@ViewData["CurrentSort"]" asp-route-currentFilter="@ViewData["CurrentFilter"]" asp-route-pageNumber="@(Model.PageIndex + 1)" class="page-btn" style="@(nextDisabled ? "pointer-events:none;opacity:0.6;" : "")"> Next </a>
内容的提问来源于stack exchange,提问作者butthash3030
相关产品推荐
相关产品推荐

