在Ajax调用后重定向到另一个页面?

时间:2018-08-17 19:30:20

标签: javascript ajax asp.net-mvc razor-pages

所以这对我来说很难尝试解释。我有一个剃须刀页面,当单击按钮时,它将调用一个javascript函数,该函数对后端的处理程序进行ajax调用。处理程序会做一些事情,并获取一个我想传递给另一个页面的ID。我正在尝试在后端使用RedirectToPage函数,但是屏幕永远不会打开。它成功调用了处理程序,但是当处理程序返回时,什么也没有发生。有办法吗?

这是通过单击按钮调用的javascript / ajax代码。

@section scripts{
<script>

// Get the account ID Data from the row selected and return that to the program.
function getIDData(el) {        

    var ID = $(el).closest('tr').children('td:first').text();
    var iddata = {
        'ID': ID
    }        

    console.log(iddata);
    return iddata;
}

// Submit the data to a function in the .cs portion of this razor page.
$('.copybtn').click(function () {
    var accountid = JSON.stringify(getIDData(this));
    $.ajax({
        url: '/Copy_Old_Account?handler=CopyData',
        beforeSend: function (xhr) {
                        xhr.setRequestHeader("XSRF-TOKEN",
                                $('input:hidden[name="__RequestVerificationToken"]').val());
                },
        type: 'POST',
        dataType: 'json',            
        data: { offenderid: offenderid },    
        success: function (result) { 

        }, 
    });
});

</script>
}

关于我从ajax调用中调用的代码背后的代码,在下面:

public ActionResult OnPostCopyData (string accountid)
{
   // Do my other stuff here
   return RedirectToPage("Account_Information", new { id = account.Account_ID });
}

我们将不胜感激,如果没有帮助,我可以尝试解决所有问题。

2 个答案:

答案 0 :(得分:1)

我认为这就是您想要的,我在MVC 5项目中做了类似的事情,但尚未在Razor Pages中对其进行测试:

这是您的方法,请注意,您应该将Controller添加到Url.Action,而且我个人没有尝试将参数与url一起传递,但是我认为它可以正常工作

[HttpPost]
public ActionResult SubmitSomething()
{
    return Json(new { redirectUrl = Url.Action("Account_Information", "YOUR_CONTROLLER_NAME", new { id = account.Account_ID }) });
}

然后这将是您的Ajax请求,我更新了success部分

// Submit the data to a function in the .cs portion of this razor page.
$('.copybtn').click(function () {
    var accountid = JSON.stringify(getIDData(this));
    $.ajax({
        url: '/Copy_Old_Account?handler=CopyData',
        beforeSend: function (xhr) {
                        xhr.setRequestHeader("XSRF-TOKEN",
                                $('input:hidden[name="__RequestVerificationToken"]').val());
                },
        type: 'POST',
        dataType: 'json',            
        data: { offenderid: offenderid },    
        success: function (result) { 
            if (result.redirectUrl !== undefined) {
                window.location.replace(result.redirectUrl);
            } else {
                // No redirect found, do something else
            }
        }, 
    });
});

这未经测试,所以我只能希望它现在对您有用

编辑:更新了Url.Action以使用OP的视图名称和参数

答案 1 :(得分:0)

重定向到页面将返回301响应,格式为:

HTTP/1.1 301 Moved Permanently
Location: http://www.example.org/index.asp

要在ajax调用后重定向,您可以通过以下方式重定向到请求的网址:

success: function (result) { 
window.location = result.getResponseHeader('Location');
}