POST 和 GET 方法在同一个按钮上

POST and GET methods on the same button

我目前正在学习 asp.net 核心 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);
            }
        });

        
    })

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

因此您的 POST 方法将首先被调用,它会调用 GET 方法。

Here 是文档。

您可以使用$.ajax 'done'链接来完成整个过程:

$('#calculateButton').on("click", function () {
    $.ajax({
        url: "/trade/calculateexchangeratio",
        data: { amount_give: 9.99, type_to_give: 'blahblah' },
        type: "post"
    })
    .done(function(){
        $.ajax({
            url: "/trade/getconvertedamount",
            type: "get"         
        })
        .done(function (amount) { console.log(amount); alert(amount); });
    });
})