Redirect to Other Page when Ajax Success


In this post I want to explain how to redirect to other pages based on Asp.net MVC Web API Controller result by using JQuery. Based on process output we need to transfer the page dynamically. For example the login user is admin we need to redirect to admin dashboard otherwise transfer to home page.  

public class FooController : ApiController
{  
    public HttpResponseMessage PostFoo(string user)
    {     
      HttpResponse response;
     If(user == “admin“)
     {
      response = Request.CreateResponse(HttpStatusCode.Moved);
      response.Headers.Location = new Uri("http://www.abcmvc.com/admin");
     }
    else{
     response = Request.CreateResponse(HttpStatusCode.Moved);
     response.Headers.Location = new Uri("http://www.abcmvc.com/home");
   }
   }
}

Now let see how to redirect the redirect the from one page to other page from Jquery

  $.ajax({
         type: 'GET',
         url: @url(“PostFoo”,../api/ FooController)’,
         data: { user:‘admin‘ },
         dataType: "json",
         success: function(res,status,XHR) {
             var _location = XHR..getResponseHeader('Location');
             window.location = _location
         },
         error: function(jqXHR) { }
      });


No comments:

Post a Comment