为什么获胜't我的AJAX帖子重定向到正确的ActionResult

Why won't my AJAX post redirect to the correct ActionResult

本文关键字:重定向 ActionResult AJAX 获胜 我的 为什么      更新时间:2023-09-26

设置非常简单,我知道我错过了一些愚蠢的东西。

JS:

$("#Affiliate").change(function () {
                var selectedItem = $(this).val();
                $.ajax({
                    cache: false,
                    type: "POST",
                    url: "@(Url.Action("ChangeOrg", "ScheduleStatistic"))",
                    data: { "organazation": selectedItem }
                });
            });

视图:

<select id="Affiliate" class="form_select" style="z-index: 3000; width: 100%;">
                                    <option value="Org1">Foo</option>
                                    <option value="Org2">Bar</option>

控制器:

 public ActionResult ChangeOrg(string organazation)
    {
        switch (organazation)
        {
            case "Org1":
                return RedirectToAction("Index", new { orgURL = "URL_Org1" });
                break;
            case "Org2":
                return RedirectToAction("Index", new { orgURL = "URL_Org2" });
                break;
            default:
                return this.View();
        }
    }

然而,当它达到行动结果时。。。但是,如果我键入URL"Localhost/ChangeOrg?Organaization=Org1",它就不会执行重定向操作。有什么想法吗?

服务器端重定向实际上是通过客户端跳闸完成的。重定向与ajax请求无关,因此浏览器从不调用重定向的url。

Index操作的预期结果是什么?您将如何在ajax的succes上使用它?

根据你真正需要的,这可能对你有用:

public ActionResult ChangeOrg(string organazation)
{
    switch (organazation)
    {
        case "Org1":
            return Index("URL_Org1");
            break;
        case "Org2":
            return Index("URL_Org2");
            break;
        default:
            return this.View();
    }
}

更新:

如果当Affiliate值更改时,用户应该重定向到不同的页面,则不需要ajax:

$("#Affiliate").change(function () {
  var selectedItem = $(this).val();
  var url = "@(Url.Action("ChangeOrg", "ScheduleStatistic"))?organazation=" + selectedItem,
  window.location.assign(url);
});
ajax不会重定向。要重定向,您需要在ajax调用时将其成功
$.ajax({
    cache: false,
    type: "POST",
    url: "@(Url.Action("ChangeOrg", "ScheduleStatistic"))",
    data: { "organazation": selectedItem }
    success: function(result){
        if(result.Success){
            window.location = "@Url.Action(newaction, newcontroller)"
        }
    }
});