Response.redirect not redirected to C #

I want to redirect to a specific site using C #. I wrote the code as:

HTML:

<button id="Buy" class="k-button">Button</button> 

Script:

  $("#Buy").live('click', function () { $.ajax({ url: "/Home/Redirect", data: JSON.stringify ({ }), cache: false, dataType: "json", success: function (str) { }, type: 'POST', contentType: 'application/json; charset=utf-8' }); }); 

WITH#:

  public ActionResult Redirect() { Response.Redirect("http://www.google.com"); return Json("suc",JsonRequestBehavior.AllowGet); } 
+6
source share
3 answers

You cannot redirect to ajax post, which will give you error 302. What you should do is return the URL from your controller method.

 public ActionResult Redirect() { return Json(the_url); } 

and then redirect from your client code:

 $.ajax({ // your config goes here success: function(result) { window.location.replace(result); } }); 
+6
source

This is because jQuery picks up a redirection statement and does nothing with it. Keep in mind that redirects are handled by the browser, not the server.

Try adding the complete callback to the AJAX call to handle the redirect command (for example, after your success callback):

 complete: function(resp) { if (resp.code == 302) { top.location.href = resp.getResponseHeader('Location'); } } 

This should handle 302 that the method returns and performs a redirect. Alternatively, return the URL in JSON as von v suggests.

+1
source

In the controller

If you want to redirect to another website, we can simply use, for example,

 public ActionResult Redirect() { //return View(); return Redirect("http://www.google.com"); } 
0
source

Source: https://habr.com/ru/post/944098/


All Articles