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);
}
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);
}
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With