How to either return JSON or RedirectToAction?

Posted by DaveDev on Stack Overflow See other posts from Stack Overflow or by DaveDev
Published on 2010-05-14T09:30:35Z Indexed on 2010/05/14 9:34 UTC
Read the original article Hit count: 522

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");
            }

        }

© Stack Overflow or respective owner

Related posts about c#

Related posts about asp.net-mvc