【问题标题】:Clicking 2 submit buttons in the same page单击同一页面中的 2 个提交按钮
【发布时间】:2021-05-05 19:14:26
【问题描述】:

我在 .Net Core 中有一个带有 Razor Pages 的项目,我有一个包含一些输入字段和 2 个提交按钮的表单。

<form class="form-style" method="post" id="createForm">
  <div class="form-group button-position col-md4">
      <input type="submit" id="placeRequest" name="placeRequest" value="Place Request" class="btn btn-primary" />
  </div>

  <div class="form-group button-position col-md4">
      <input type="submit" value="GetHour" asp-page-handler="Hour" class="btn btn-primary btn-style" formnovalidate />
  </div>
</form>

我需要能够单击第一个提交按钮 (GetHour),然后单击第二个提交按钮 (Placer Request)

在我的 Razor 页面模型中

 public async Task<IActionResult> OnPost()
{
   //code that will be executed when the Place Request button is clicked
}

 public async Task OnPostGetHour()
 {         
    ////code that will be executed when the Get Hour button is clicked
 }

问题是我不允许提交 2 次。如果我只做其中一个,它可以工作,但第二个什么都不做

有什么方法可以同时提交吗?

【问题讨论】:

标签: c# forms


【解决方案1】:

这是因为一旦你点击第一个提交按钮,页面就会重定向并再次加载。

这是表单提交的本质。如果要单击这两个按钮。将按钮类型从“提交”更改为“按钮”。

然后创建 2 个点击处理程序并使用 Ajax 处理表单提交

<form class="form-style" method="post" id="createForm">
  <div class="form-group button-position col-md4">
      <input onclick="onBtn1Click()" type="button" id="placeRequest" name="placeRequest" value="Place Request" class="btn btn-primary" />
  </div>

  <div class="form-group button-position col-md4">
      <input onclick="onBtn2Click()" type="button" value="GetHour" asp-page-handler="Hour" class="btn btn-primary btn-style" formnovalidate />
  </div>
</form>

然后写2个JavaScript函数

function onBtn1Click()
{
  //Submit code via Ajax here
}

function onBtn2Click()
{
  //Submit code via Ajax here
}

【讨论】:

  • 问题是第一个按钮将提交一些我需要在我的 C# 代码中使用的数据(在 Razor 页面模型中)。 Ajax 是否允许向模型发送数据?
  • 使用局部视图绑定可以轻松实现
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-18
  • 1970-01-01
  • 2017-07-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多