ASP.NET MVC – RedirectToAction()

This Blog tags : ,
The effect of calling the function RedirectToAction() from a controller action actually triggers a header http response to be sent to browser to tell it to redirect to provided action method. So the browser then initiates a new HTTP GET request to the new action method URL.
What happens if we call the action method directly like return Index(). It is simply a method call which returns a rendered view. This is similar of ASP.NET Request.Redirect() and Server.Transfer() when working with WebForms.
The important (and useful) difference is that in case of direct call the HTTP request context remains same from calling action to called action whereas it changes in case of redirect.
Here is a useful code snippet we can use to render partialview depending on an Ajax call from the same action method.
   1:  public ActionResult Index()
   2:  {            
   3:     var businessObjects = _businessObjectsRepository.FindAll();
   4:     if(Request.IsAjaxRequest())               
   5:         return View("_BusinessObjectsList", sessions);
   6:     return View(businessObjects);
   7:  }




Now we can use this conditional partial or full listing view render after adding a new object:

   1:  [AcceptVerbs(HttpVerbs.Post)]
   2:  public ActionResult Add(BusinessObject obj)
   3:  {            
   4:     _businessObjectsRepository.SaveObject(obj);
   5:     if(Request.IsAjaxRequest())               
   6:         return Index();
   7:   
   8:     return RedirectToAction("Index");
   9:  }



Comments