简体   繁体   中英

calling action method from Jquery and redirecting the user to an external site

I would like to call the mvc controller action method from jQuery, and when the action method gets invoked, the user should be transferred to another site. I have tried using jquery ajax to do this but after response.redirect, my page still stays on the same URL with out any change.

 $.ajax({
        url: '/Controller/Action',
        success: function (Data) {
        //don't want to use this callback as I require only calling the 
        action method
        }
    });

and in the controller

public void Action(){
  // process the request and redirect
    Response.Redirect("url", false);
 }

Can anyone help me in understanding where the issue is in the above code.

Thanks in advance.

You can try something like this

return Redirect("http://www.google.com");

or try using javascript

public ActionResult Index()
{
 return Content("<script>window.location = 'http://www.example.com';
 </script>");
}

You can check this link to know about Redirect vs RedirectResult

return new RedirectResult() vs return Redirect()

I tried it and it is working. I hope this helps :-)

HTML

 <button class="btn btn-primary" onclick="RedirectTosite()">Redirect To Google</button>

Jquery Call

function RedirectTosite() {
    $.ajax({
        url: '/Employee/RedirectTosite',
        success: function (Data)
        {
            window.location = Data;              
        }
    });
}

Controller

 public JsonResult RedirectTosite()
    {
        return Json("http://www.google.com", JsonRequestBehavior.AllowGet);
    }

I don't get a clue why are you calling server using ajax if you don't do any data manipulation on the database if you are aiming just to redirect to a page simply redirect using javascript code like

window.location.href = '/Controller/Action/'

Ok I am convinced you have done some work on the void method, If you redirect page on the void method ajax request fails and you are not redirected to another page. For it to work you simply remove the line of code

    Response.Redirect("url", false);

from controller and write a line of code as follows inside success function of ajax .

window.location.href = '/Controller/Action/'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM