首页 > 解决方案 > POST 和 GET 方法在同一个按钮上

问题描述

我目前正在学习 asp.net core 3,但我找不到任何关于这个问题的帮助。我有一个通过 POST 请求提交值的表单。但我希望在同一个按钮上有一个 GET 请求,该请求用 .ajax / xmlhttprequest 填充另一个字段。但我希望先执行 POST 方法,然后执行 GET 方法。有可能做到吗?我试过这样做,但我卡住了。

这些是我的控制器内部的方法。

[HttpGet]
public async Task<IActionResult> GetConvertedAmount()
{
    var rate = await _db.ExchangeRates.Where(x => x.Name.Equals(_tM.Currency)).ToListAsync();         
    _tM.convertToCurrency(rate[0].Rate);
    var amount = _tM.Amount;           
    return Json(amount);           
}

[HttpPost]
public ActionResult CalculateExchangeRatio(int amount_give, string type_to_give)
{
    _tM.Amount = amount_give;
    _tM.Currency = type_to_give;
    return Ok();
}

这是我的 JS 脚本

$('#calculateButton').on("click", function () {
        $.ajax({
            url: "/trade/getconvertedamount",
            type: "get",
            success: function (amount) {
                console.log(amount);
                alert(amount);
            }
        });

        
    })

标签: javascriptc#asp.net-core-3.1

解决方案


您可以在 POST 方法实现的末尾添加类似的内容return RedirectToAction("CalculateExchangeRatio", new { amount_give = 1, type_to_give = 2 });

所以你的 POST 方法将首先被调用,它会调用 GET 方法。

是文档。


推荐阅读