Following the NerdDinners example, I am interested in creating a strongly typed Master Page. In order to achieve this, I use a base controller which retrieves the data for t
You could create an after action executed filter which looks for a model of that type and sets the properties accordingly, perhaps by calling a base controller function. You would then put the filter on the base class, and all actions would see it automatically.
The action filter attribute gets the controller's ViewModel
, and passes it to the controller's SetModel
function:
using System.Web.Mvc;
using Site1.Controllers;
namespace Site1.Models
{
public class MasterAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
base.OnActionExecuted(filterContext);
MasterViewModel viewModel = (MasterViewModel)((ViewResultBase)filterContext.Result).ViewData.Model;
BaseController controller = (BaseController)filterContext.Controller;
controller.SetModel(viewModel);
}
}
}
This function is added to the BaseController
:
public void SetModel(MasterViewModel childViewModel)
{
childViewModel.Buttons = model.Buttons;
}
Rather than creating an attribute, why not just override Controller.OnActionExecuted and put the initialization code there? Seems a bit simpler.