ProgrammerGuide.Net | Step by Step Programmer Guide

How do I Specify Different Layouts In The ASP.NET MVC Programatically? | ASP.NET MVC


There might be a scenario where you want to have more than one layout in asp.net MVC. Let say one is for the Home Page of the website and the other is for the Admin of the website.

In the default Asp.Net MVC Internet Application, we have HomeController and AccountController. I wan’t to set Home Page layout to Index view and Admin layout for Login view. Below is the Layout cshtml for example.

  • _HomePageLayout.cshtml
  • _AdminLayout.cshtml

How do we set these layouts to the view? How to set the layout _HomePageLayout.cshtml to Index view and _AdminLayout.cshtml to Login view diagrammatically?

We can achieve this by specifying which layout should be used when returning a view inside a controller action with the help of extended ActionFilterAttribute. Given below is the custom action filter which would override the layout for the action.

Action filter which would choose a master page:

public class LayoutInjecterAttribute : ActionFilterAttribute
{
    private readonly string _masterName;
    public LayoutInjecterAttribute(string masterName)
    {
        _masterName = masterName;
    }

    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);
        var result = filterContext.Result as ViewResult;
        if (result != null)
        {
            result.MasterName = _masterName;
        }
    }
}

and then decorate a controller or an action with this custom attribute specifying the layout you want

[LayoutInjecter("_PublicLayout")]
public ActionResult Index()
{
    return View();
}

Rajesh MG

Rajesh MG is a software engineer, reader and writer from India. He has worked in various .Net projects. Follow him on twitter @rajeshmgonline

Please click here for related products on Amazon!

Jayashee

Add comment

Want to Check Celebrities News?