asp.netasp.net-mvcmaster-pages

ASP.NET MVC - Set Master View accordingly with Controller


By any chance, is there any easy way to set a default MasterView for all the actions inside a specific controller?

For example If I have the HomeController I want all the actions inside it to inherit the Site.Master as default, but If I am inside AccountsController I want all the action to inherit the Admin.Master and so on..

I managed to do it with:

return View("viewName", "masterName", objectModel);

But by doing this I have to apply it every time I call the View method.

I was looking for something simpler like on rails where we can declare:

class HomeController < ApplicationController

  layout 'site'

   def index
   end

   def create
   ...

end

class AccountsController < ApplicationController

  layout 'admin'

  def index
  end

  def create
  ...  

end

Is that possible?

Thanks in advance


Solution

  • You could override OnActionExecuting in that Controller class.

    protected override void OnActionExecuting(ActionExecutingContext filterContext) 
    { 
        ViewData["MasterfileToUser"] = "site";
    }       
    

    Or if you like you can turn this into an ActionFilterAttribute you can apply on the controller or action level

    using System;
    using System.Web.Mvc;
    public class MasterFileFilterAttribute : ActionFilterAttribute
    {
        public string Master { get; set; }
    
        public override void OnActionExecuted( ActionExecutedContext filterContext)   
        {        
                if (filterContext.Result is ViewResult)
                        ((ViewResult)filterContext.Result).MasterName = Master;
        }
    }
    

    which you then in turn use like so:

    [MasterFileFilterAttribute(Master = "site")] 
    public class HomeController : Controller 
    { 
        // Action methods 
    }