Layout Filter

The LayoutAttribute provides an alternative mechanism for specifying the Master Page (aka layout) to use when rendering a view.

Usually, if you want to specify a custom MasterPage to use when rendering a view, you would call the View method with an additional argument:

public class MyController : Controller 
{
	public ActionResult Index() 
	{
		return View("Index", "MyCustomMasterPage");
	}
}


This approach has some disadvantages:
  • You have to explicitly specify the view name
  • If you want to use the custom master page for all actions in a controller, you have to modify every action

The LayoutAttribute allows you to specify the master page without having to modify your actions.

using MvcContrib.Filters;

public class MyController : Controller 
{
	[Layout("MyCustomMasterPage")]
	public ActionResult Index() 
	{
		return View();
	}
}


If you apply the attribute at the Controller level, then that layout will apply to every action in the controller.

[Layout("MyCustomMasterPage")]
public class MyController : Controller 
{
	public ActionResult Index() 
	{
		return View();
	}

	public ActionResult About() 
	{
		return View();
	}
}


Note that you can still override the layout by explicitly specifying the master page in the action

[Layout("MyCustomMasterPage")]
public class MyController : Controller 
{
	public ActionResult Index() 
	{
		return View();
	}

	public ActionResult About() 
	{
		return View("About", "DifferentMasterPage");
	}
}

Last edited Jul 20, 2008 at 2:47 PM by JeremyS, version 1

Comments

No comments yet.