0

This is a continuation from my question last night. I have a JQuery AJAX response, as below. I just need this to redirect to another view. See my code:

      $.ajax({
            url: "/Home/PersistSelections",
            type: 'post',
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            data: JSON.stringify(selectedItems),


            done: function (response) {
                window.location.href = "Home/GoToBooking";
            }
        })

The code in done, does not seem to work. I have also tried success. I'm also not sure what the parameter should be (response, or something else?).

In addition, I have seen code like this:

return JavaScript("window.location = 'http://www.google.co.uk'");'

I have JavascriptResult resolving in my controllers, but when I try to use return Javascript, I can't seem to resolve the references? I am using ASP.NET Core 2.2.

MaartenDev
  • 5,631
  • 5
  • 21
  • 33
Bladerider1
  • 41
  • 1
  • 7

3 Answers3

0

Try replacing -

    done: function (response) {
        window.location.href = "Home/GoToBooking";
    }

With -

        success: function (response) {
            window.location.href = "/Home/GoToBooking";
        }
bsod_
  • 903
  • 8
  • 27
0

In controller instead of JavascriptResult Use IActionResult

In Js Use like this

$.ajax({
url: '//',
type: 'POST',
async: false,
data: { Your data },
success: function (data) {
    window.location.href = "/Home/Index";
 }
});
Ishwar Gagare
  • 723
  • 3
  • 9
0

First,you need to be sure that the return data type is json because you set dataType:"json" in ajax.

Then done method should be used like below:

$.ajax({
        url: "/Home/PersistSelections",
        /....
     })
         .done(function (response) {
            window.location.href = "/Home/GoToBooking";
     })

Referece:jQuery.ajax handling continue responses: "success:" vs ".done"?

Finally,the href should be /Home/GoToBooking.

Here is a working sample you could refer to:

1.View:

<button onclick="test()">click</button>

@section Scripts
{
<script>
    function test() {
        var selectedItems = { Id: 1, Namea: "aaa" };
         $.ajax({
            url: "/Home/PersistSelections",
            type: 'post',
            contentType: "application/json; charset=utf-8",
            dataType: 'json',
            data: JSON.stringify(selectedItems)
         })
             .done(function (response) {
                window.location.href = "/Home/GoToBooking";
         })
    }
</script>
}

2.Controller:

[HttpPost]
public JsonResult PersistSelections([FromBody]Test test)
{
    return new JsonResult(test);
}
Rena
  • 30,832
  • 6
  • 37
  • 72