【问题标题】:data-ajax-begin script in ASP.Net Core MVC blocks redirectionASP.Net Core MVC 中的 data-ajax-begin 脚本阻止重定向
【发布时间】:2017-05-23 03:29:42
【问题描述】:

我正在尝试在 ASP.NET Core 中创建简单的微调器,该微调器将在控制器操作持久时显示。

代码按预期工作,但它似乎阻止了控制器操作中的重定向。 在这种情况下有什么方法可以使重定向工作吗?

我的索引.cshtml

<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/jquery-ajax-unobtrusive/src/jquery.unobtrusive-ajax.js"></script>

<script type="text/javascript">
    function onBegin() {
        $("#divLoading").html('<image src="~/images/ajax-loader.gif" alt="Loading, please wait" />');
    }
    function onComplete() {
        $("#divLoading").html("");
    }
</script>

<form data-ajax="true" data-ajax-begin="onBegin" data-ajax-complete="onComplete" asp-action="LoadLongLasting" asp-controller="Home">
    <input type="submit" value="Load Long lasting"/>
</form>
<div id="divLoading"></div>

控制器动作示例:

    public ActionResult LoadLongLasting()
    {
        bool result = GetLongLastingResult();

        if(result)
        {
            return View();
        }

        return RedirectToAction("Error");
    }

【问题讨论】:

  • ajax 的全部意义在于保持在 same 页面上。 Ajax 调用从不重定向,因此您的 return RedirectToAction("Error"); 毫无意义
  • 好的,那么在没有 Ajax 的情况下,在请求开始时显示已实现的微调器并在其末尾隐藏的最佳实践是什么。我相信这是一个很常见的情况,但老实说我不知道​​。

标签: asp.net-mvc asp.net-core asp.net-ajax


【解决方案1】:

你需要像这样在 onSuccess 函数中返回 json 并编写重定向。

查看:

<script type="text/javascript">
    function onBegin() {
        $("#divLoading").html('<image src="~/images/ajax-loader.gif"
alt="Loading, please wait" />');
    }
    function onSuccess() {
        if(data.status === 1) {
            window.location.href = "/yourpage";
        }
    }
    function onComplete() {
        $("#divLoading").html("");
    }
</script>

<form data-ajax="true" data-ajax-begin="onBegin" data-ajax-complete="onComplete" data-ajax-success="onSuccess" asp-action="LoadLongLasting" asp-controller="Home">
    <input type="submit" value="Load Long lasting"/>
</form>

控制器:

public ActionResult LoadLongLasting()
{
    bool result = GetLongLastingResult();

    if(result)
    {
        return View();
    }
    return Json(new { status = 1 });
    //return RedirectToAction("Error");
}

【讨论】:

    猜你喜欢
    • 2011-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-15
    相关资源
    最近更新 更多