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:
If this method returns 'ActionResult', then I'm getting the error not all code paths return a value
.
If I use 'void', I cannot return anything.
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?
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; } });
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