How to return JSON or RedirectToAction?

I have an action method that I would either return JSON from one condition or redirect to another condition. I thought I could do this by returning an ActionResult from my method, but this leads to the error "not all code paths return a value"

Can someone tell me what I am doing wrong? Or how to achieve the desired result?

Here is the code below:

[AcceptVerbs(HttpVerbs.Post)] public ActionResult Login(User user) { var myErrors = new Dictionary<string, string>(); try { if (ModelState.IsValid) { if (userRepository.ValidUser(user)) { RedirectToAction("Index", "Group"); //return Json("Valid"); } else { return Json("Invalid"); } } else { foreach (KeyValuePair<string, ModelState> keyValuePair in ViewData.ModelState) { if (keyValuePair.Value.Errors.Count > 0) { List<string> errors = new List<string>(); myErrors.Add(keyValuePair.Key, keyValuePair.Value.Errors[0].ErrorMessage); } } return Json(myErrors); } } catch (Exception) { return Json("Invalid"); } } 

Edit: to clarify, I already tried return RedirectToAction("Index", "Group"); as suggested in the answers, but does nothing. The breakpoint in action that I am redirecting to does not fall.

+6
c # asp.net-mvc jsonresult redirecttoaction
source share
4 answers

You need to change

 RedirectToAction("Index", "Group"); 
from

before

 return RedirectToAction("Index", "Group"); 
+3
source share

you release the return of RedirectResult. Change this line

 if (userRepository.ValidUser(user)) { RedirectToAction("Index", "Group"); //return Json("Valid"); } 

to

 if (userRepository.ValidUser(user)) { return RedirectToAction("Index", "Group"); //return Json("Valid"); } 

and everything will work fine.

0
source share

Invalid return statement:

 return RedirectToAction("Index", "Group"); 

The Controller.RedirectToAction method returns a RedirectToRouteResult and the Controller.Json method returns a JsonResult . Both are ActionResult extensions.

0
source share

I think the reason your redirecting is not where you want it is because it redirects to an action that only Gets takes, and you redirect the message.

0
source share

All Articles