Experimenting on the internet through ideas and innovation to make a life a little better for the current and next generations.
Rate this page
The ASP.NET MVC implemented _ViewStart.cshtml as a way to DRY (Do not Repeat Yourself) the Layout definition in every single view page specially if all view pages use the same layout. What if you now want to use multiple layouts based on your user settings?
I have been trying to put conditional codes using ViewBag to pass parameters from the Controller to the _VIewStart.cshtml file but it doesn't work because ViewBag is inherited from System.Web.Mvc.WebViewPage which seems to be not accessible from the _ViewStart.cshtml file.

All the internet search about MVC view start so far provides a simple use using the Layout property.

The Layout property is actually derived from System.Web.Mvc.ViewStartPage class and you can access the reference from the MSDN site here. So according to this page, The ViewContext is available and good thing is ViewData resides under ViewContext. So to solve my problem of implementing multiple layouts base on user setting, it turn out to be an easy task from here. I modified the _ViewStart.cshtml file like this


@{
                
// Layout = "~/Views/Shared/Layout/_Layout.cshtml";
    Layout = (String)ViewContext.ViewData["Layout"];
    
}


In the Controller I can the set the Layout object value but I think the best place to do that is in the ApplicationController like so


@{
                
 // ViewBag.Layout =  db.UserSetting(p=>p.param="Layout");
           ViewBag.Layout =  "~/Views/Shared/Layout/_LayoutView1.cshtml";
    
}



Summary

In summary, using multiple layouts in ASP.NET MVC 3 is relatively simple task. There could be a better solution than the above technique but the approach seems to be simplified already.
Tags: Mvc
Rate this page

 

Comment Form

COMMENTS


X