【问题标题】:.Net Core MVC - How to submit an MVC form to an actionMethod with Route attribute which includes params.Net Core MVC - 如何将 MVC 表单提交给具有包含参数的 Route 属性的 actionMethod
【发布时间】: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


【解决方案1】:

假设您的控制器名称是PropController

@using (Html.BeginForm("Search", "Prop", new
{
    location = "somewhere",
    category = "something",
    p = 1
}))
{
    <input name="q"/>
}

使参数可选。

[Route("Prop/{location}/{category}/{p}")]
public IActionResult Search(string location, string category, int p, string q = null)
{
    var vm = new ReloadVm();
    // rest of the code 
    return View(vm);
}

或者使用模型绑定

public class Model
{
    public string q { get; set; }
}
[Route("Prop/{location}/{category}/{p}")]
public IActionResult Search(string location, string category, int p, MyModel m)
{
    var q = m?.q;
    var vm = new ReloadVm();
    // rest of the code 
    return View(vm);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-20
    • 2022-01-09
    • 2013-01-10
    • 2021-09-05
    • 2017-02-26
    • 1970-01-01
    相关资源
    最近更新 更多