I have an Action Method that I'd either like to return JSON from on one condition or redirect on another condition. I thought that I could do this by returning ActionResult from my method but doing this causes the error "not all code paths return a value"
Can anyone tell me what I'm doing wrong? Or how to achieve the desired result?
Here's 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've already tried to return RedirectToAction("Index", "Group");
as suggested in the answers but it doesn't do anything. The breakpoint in the action I'm redirecting to doesn't get hit.
You need to change
RedirectToAction("Index", "Group");
to
return RedirectToAction("Index", "Group");
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