Search code examples
c#asp.net-mvcfacebook-canvas

Defining Layout for the View in OnActionExecuted


In an MVC 5.1 web application project, I have a controller that is dedicated to the Facebook Canvas Application of the project. I need all the Views returned by the controller to have a specific Layout. (Normally, I would not define the Layout property in the controller for it would have too much to say on the View, but in this case I'm willing to let the controller dictate this since it's all about the facebook canvas).

I can achieve this by returning

return View("View", "~/Views/Shared/_FacbookCanvasLayout.cshtml");

but in that case I'd have to use this for every single view. What I want instead is to override the OnActionExecuted method in a base controller class and define the layout there.

So my question is, how can I define the layout for the view in the OnActionExecuted class - or if there is a better solution for this, how can I do that?


Solution

  • How about doing it this way then ?

        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            base.OnActionExecuted(filterContext);
            var res = filterContext.Result as ViewResult;
            if (res != null)
                res.MasterName = "~/Views/Shared/_FacbookCanvasLayout.cshtml";
        }