Apr 29, 2010

Loading common model into view

In our view, there are some data which are require across all page, such as site bar data, menu, and so on. We can split them into partial view and using Html.RenderAction. But this should not be overused, because of performance issue and also it kind of violate separation of concerns. In this case, the view is controlling data. If we want to use Html.RenderPartial, data can be explictly passed in Parent View, or we can inject the data into ViewData in the stack before ActionResult is returned from controller. For example, we can use base controller, and override

public void BaseController : Controller
{
    protected override OnActionExecuting(ActionExecutingContext context)
    {
        ViewData.Add(your_data);
    }
}

Another option is use ActionFilterAttribute. It is designed to solve cross-cutting concerns, like authorization, logging and so on. But we can use it to load common data as well.


public class RequireCommonDataAttribute : ActionFilterAttribute
{
   public override void OnActionExecuting(ActionExecutionContext filterContext)
   {
        filterContext.Controller.ViewData.Add(your_data);

   }
}

public class MyController
{
   [RequireCommonDataAtrribute]
   public ActionResult View()
   {
    }
}