Search code examples
c#model-view-controllerasp.net-mvc-5

How can I redirect from void method to a view?


[HttpGet]
public void verifyAccount(string id)
{
    if (clientDB.verifyAccount(id)!="")
    {
       Redirect("index"); //redirect to index view, but does not work
    }
    else
    {
        //redirect to error view
    }
   
}

I try to use Redirect("Index"); but it does not work, is it impossible to redirect to view from a void method?


Solution

  • You cannot redirect from a method that returns void. In order to redirect, you must return an ActionResult, and since this method returns nothing, you obviously cannot achieve that.

    Setting the return type of an action to void is just a simplistic way of saying it returns a response with a 200 status code and no response body. If that's not actually the case, as it isn't here, then you should not have a return type of void. Here, the only response possible is a redirect, so your action should have a return type of either ActionResult or RedirectResult. It's generally better to just use ActionResult for everything though, as it's the base class for all other types of results. You can even achieve the same thing as if you used void by doing return new EmptyResult(); or simply return null;.