簡體   English   中英

為什么我的AJAX帖子不會重定向到正確的ActionResult

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

這么簡單的設置,我知道我在這里錯過了一些愚蠢的東西。

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();
        }

    }

然而,當它到達那個動作結果時...它永遠不會執行redirectToAction但是如果我輸入URL“Localhost / ChangeOrg?Organazation = 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)"
        }
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM