Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Server side redirection after jquery ajax call in asp.net mvc 4

Tags:

I am sending login information from a jQuery AJAX call to an MVC 4 controller:

   $.post(url, data, function (response) {       if (response=='InvalidLogin') {           //show invalid login       }       else if (response == 'Error') {           //show error       }       else {           //redirecting to main page from here for the time being.           window.location.replace("http://localhost:1378/Dashboard/Index");       }    }); 

If the login is successful, I want to redirect a user from the server-side to the appropriate page on the basis of user type. If the login fails, a string is sent back to user:

    [HttpPost]     public ActionResult Index(LoginModel loginData)     {         if (login fails)         {             return Json("InvalidLogin", JsonRequestBehavior.AllowGet);         }         else         {              // I want to redirect to another controller, view, or action depending              // on user type.         }     } 

But there are problems:

  1. If this method returns 'ActionResult', then I'm getting the error not all code paths return a value.

  2. If I use 'void', I cannot return anything.

  3. Even if I use 'void' with no return, I am failing to redirect to other controller or view due to asynchronous nature of jQuery AJAX calls.

Are there any techniques to handle such scenarios?

like image 708
s.k.paul Avatar asked Nov 05 '13 17:11

s.k.paul


1 Answers

return usually returns from method without executing any further statements in it so else part is not needed. This way you will get rid of a problem #1.

As for redirecting why not return some kind of redirect command:

[HttpPost] public ActionResult Index(LoginModel loginData) {     if (login fails)     {         return Json(new {result = "InvalidLogin"}, JsonRequestBehavior.AllowGet);     }     return Json(new {result = "Redirect", url = Url.Action("MyAction", "MyController")}); } 

And then in javascript:

$.post(url, data, function (response) {   if (response.result == 'InvalidLogin') {       //show invalid login   }   else if (response.result == 'Error') {       //show error   }   else if (response.result == 'Redirect'){       //redirecting to main page from here for the time being.       window.location = response.url;   }  }); 
like image 117
Ramunas Avatar answered Oct 06 '22 01:10

Ramunas