【发布时间】:2020-11-23 21:15:00
【问题描述】:
我正在尝试使用包含参数的自定义路由向ActionMethod 提交表单。
[Route("Prop/{location}/{category}/{p}")]
public IActionResult Search(string location, string category, int p, string q)
{
var vm = new ReloadVm();
// rest of the code
return View(vm);
}
如果我使用Html.BeginForm 而不是404,因为它将尝试加载https://localhost:44326/prop/search 而不是自定义路由。以前我使用过window.location.href,但有人告诉我它不适合谷歌,现在Chrome 取消了这个Javascript 调用的url 请求,所以它似乎不稳定。
处理这个问题的最佳方法是什么?
另外,这个动作方法有大约 15 个参数,为了保持 url 干净,我想只传回不为 null 或 0 的参数,所以我最终会得到一个 url 像 @987654331 @。
更新 - window.location.href 有效,“触发”按钮必须定义为 type=button 否则它将取消 JS 请求并将其视为提交。
在没有JS的情况下仍在寻找更好的方法
【问题讨论】:
-
在 BeginForm 中使用您的参数提供控制器和操作名称。
-
您也可以在表单提交事件或按钮点击事件中使用
type="submit"和event.PreventDefault()。 -
你能显示你的视图代码吗?带有
Html.BeginForm的那个,因为我看不到您如何设置表单的操作。 -
这能回答你的问题吗? Using Html.BeginForm() with custom routes
-
你可以像这样使用`@using (Html.BeginForm("xxx", "Prop", FormMethod.Post, new { location= @Model.location,FormMethod.Post, enctype = "multipart /form-data" })) { `,但它不能只传递非空参数给url,它会传递你在BeginForm中设置的所有参数
标签: javascript asp.net-core model-view-controller .net-core asp.net-core-mvc