1

so this is a hard one for me to try and explain. I have a razor page that when a button is clicked it calls a javascript function which makes an ajax call to a handler in the back end. The handler does some stuff and gets a id that I want to pass to another page. I am trying to use the RedirectToPage function in the back end but the screen never opens. It successfully calls the handler but when the handler does its return, nothing happens. Is there a way to do this?

Here is the javascript/ajax code that gets called from a button being clicked.

@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>
}

For my code behind code that I am calling from the ajax call, that's below here:

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

Any help would be appreciated and if doesn't make sense, I can try and clear up any questions.

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
Jestes
  • 91
  • 2
  • 2
  • 9
  • Have you try to return the id, and then redirect in the success state from the ajax request? – joseatchang Aug 17 '18 at 19:42
  • @joseatchang I have not tried that and I'm not sure exactly how to do that. Do you have any examples I could look at? – Jestes Aug 17 '18 at 20:28
  • look into the first answer, he's referring to the object pass to `ajax` method, success will trigger once it gets an positive response for the request. – joseatchang Aug 17 '18 at 20:31
  • A vanilla html form might be a better choice over ajax, since you’re not trying to send/retrieve data without reloading the page. – James Aug 17 '18 at 20:39
  • 1
    Possible duplicate of [How to manage a redirect request after a jQuery Ajax call](https://stackoverflow.com/questions/199099/how-to-manage-a-redirect-request-after-a-jquery-ajax-call) – Erik Philips Aug 17 '18 at 21:03
  • The whole point of using ajax is to **stay on the same page**. If you want to redirect, do not use ajax - its pointless –  Aug 17 '18 at 22:42

2 Answers2

3

I think this is what you want, I did something similar in an MVC 5 project and I haven't tested it in Razor Pages yet:

This would be your method, note that you should add your Controller to the Url.Action, and I personally haven't tried passing a parameter along with the url but I image it'll work just fine

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

And then this would be your Ajax request, I updated the success portion

// 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
            }
        }, 
    });
});

This isn't tested, so I can only hope that it works for you right now

Edit: Updated the Url.Action to use OP's view names and parameters

Ryan Taite
  • 789
  • 12
  • 37
  • 1
    this answer helped me get to what I needed. I for some reason could not get url.action to work for me but I kept tweaking it until I got my answer below to work: return new JsonResult(new { path = "Account_Information?=" + offender.Account_ID.ToString()}); for my ajax I used window.location.replace as stated in your answer and this worked perfectly. – Jestes Aug 20 '18 at 14:16
0

Redirect to page returns a 301 response, which will be in the format:

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

To redirect after the ajax call you can redirect to the requested url by:

success: function (result) { 
window.location = result.getResponseHeader('Location');
}
Aman B
  • 2,276
  • 1
  • 18
  • 26
  • How to continue run ajax call after redirect to another page in PHP? My ajax call is performing a very complex task and it will take a long time So, Is it possible to run an ajax call after page redirect? I make ajax call on submit button click and after that page redirects on another page and then my ajax call is started. – JD Savaj Dec 09 '19 at 05:26