Thursday, September 11, 2014

A super simple OnActionExecuting/OnActionExecuted example.

using System.Web.Mvc;
namespace InterstateHighway.Controllers
{
   public class HomeController : Controller
   {
      protected override void OnActionExecuting(ActionExecutingContext filterContext)
      {
         ViewBag.Number = 1;
         base.OnActionExecuting(filterContext);
      }
      
      protected override void OnActionExecuted(ActionExecutedContext filterContext)
      {
         ViewBag.Number = ViewBag.Number + ViewBag.Number;
         base.OnActionExecuted(filterContext);
      }
      
      public ActionResult Index()
      {
         ViewBag.Number = ViewBag.Number + ViewBag.Number;
         return View();
      }
   }
}

 
 

...if our action above takes us to a view which looks like this...

<p>@ViewBag.Number</p>

 
 

...then the number 4 will be displayed in the view.

No comments:

Post a Comment