Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Response.redirect is not redirecting in c#

Tags:

c#

asp.net-mvc

I want to redirect to certain website using c#. I have written the code like:

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

c#:

   public ActionResult Redirect()
    {
        Response.Redirect("http://www.google.com");          
        return Json("suc",JsonRequestBehavior.AllowGet);
    }
like image 602
Jonathan Avatar asked May 02 '13 05:05

Jonathan


2 Answers

You cannot do a redirect on an ajax post, that will give you a 302 error. What you should be doing is to return the url from you 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);
    }
});
like image 82
von v. Avatar answered Oct 19 '22 10:10

von v.


This is because jQuery is picking up the redirect instruction and doing nothing with it. Bear in mind that redirects are handled by the browser, not the server.

Try adding a complete callback to your AJAX call to handle the redirect instruction (e.g. after your success callback):

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

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

like image 35
Ant P Avatar answered Oct 19 '22 10:10

Ant P