单击ASP.NET Core禁用按钮

sag*_*agi 2 c# entity-framework asp.net-core

我有一个论坛,我接受来自用户的参数,并使用这些参数在我的DB上启动一个过程.

我有点卡住了,我需要做什么:

  • 单击按钮后禁用该按钮,直到SP完成,然后再次启用它.

我的论坛:

   <form asp-action="RunProcedure" asp-controller="Home">
        <div asp-validation-summary="ModelOnly"></div>
        <div class="form-group">
            <label asp-for="ShiaruchDate">Shiaruch Date</label>
            <input asp-for="ShiaruchDate" placeholder="YYYY-MM-DD 00:00:00" class="form-control" />
            <span asp-validation-for="ShiaruchDate" class="text-muted"></span>
        </div>

        <div class="form-group">
            <p>Please enter dates in format of : YYYY-MM-DD 00:00:00</p>
            <input type="submit" />
        </div>
Run Code Online (Sandbox Code Playgroud)

我的控制器:

[HttpPost]
public async Task<IActionResult> RunProcedure(string startDate, string endDate, string shiaruchDate)
{
    if (ModelState.IsValid)
    {
        using (var cmd = _context.Database.GetDbConnection().CreateCommand())
        {
            cmd.CommandText = "RunSSISPackage";
            cmd.CommandType = CommandType.StoredProcedure;
            // set some parameters of the stored procedure
            cmd.Parameters.Add(new SqlParameter("@param3", SqlDbType.NVarChar)
            {
                Value = shiaruchDate
            });
            if (cmd.Connection.State != ConnectionState.Open)
                cmd.Connection.Open();
            cmd.ExecuteNonQuery();
        }
    }
    if (await _ISSISRepository.SaveChangesAsync())
    {

    }
    ModelState.Clear();
    return View();
}
Run Code Online (Sandbox Code Playgroud)

如何在点击时禁用按钮?

我创造了SaveChangesAsync():

    public async Task<bool> SaveChangesAsync()
    {
        return (await _context.SaveChangesAsync()) > 0;
    }
Run Code Online (Sandbox Code Playgroud)

检查程序是否完成 - 我对此是否正确?如果是,如何在控制器上的这种情况下再次启用按钮?

Mar*_*und 9

问题在于服务器上的代码不是在后台执行,而是基于用户发送的请求.

当用户单击该按钮时,将创建一个新的POST请求,并将数据发送到服务器.在发生这种情况时,用户仍然可以看到原始页面,因此她可以反复单击该按钮(有效地发送另一个您要避免的请求).

不幸的是,因为服务器上的代码与客户端是分开的,所以你不能禁用C#代码中的按钮,但是你需要在客户端使用JavaScript禁用它以防止双重提交.

你可以这样做:

<form asp-action="RunProcedure" asp-controller="Home" 
      onsubmit="theButton.disabled = true; return true;">
      ... rest of the form
      <input type="submit" name="theButton" value="Submit">
</form>
Run Code Online (Sandbox Code Playgroud)

  • 此解决方案不考虑表单验证。如果表单验证失败,则将永久禁用“提交”按钮。 (3认同)