Jonathan
Jonathan

Reputation: 1669

Response.redirect is not redirecting in c#

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

Upvotes: 7

Views: 2349

Answers (3)

Manikandan Sethuraju
Manikandan Sethuraju

Reputation: 2893

In Controller,

If you want to redirect a another website, simply we can use like,

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

Upvotes: 0

Ant P
Ant P

Reputation: 25221

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.

Upvotes: 1

von v.
von v.

Reputation: 17108

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

Upvotes: 7

Related Questions