How to create a strongly typed master page using a base controller in ASP.NET MVC

后端 未结 2 1080
一生所求
一生所求 2020-12-02 13:59

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

相关标签:
2条回答
  • 2020-12-02 14:13

    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;
    }
    
    0 讨论(0)
  • 2020-12-02 14:13

    Rather than creating an attribute, why not just override Controller.OnActionExecuted and put the initialization code there? Seems a bit simpler.

    0 讨论(0)
提交回复
热议问题