MVC3 Razor - Is there a way to change the Layout d

2019-04-09 20:37发布

问题:

I followed this tutorial with success: http://www.hanselman.com/blog/MixMobileWebSitesWithASPNETMVCAndTheMobileBrowserDefinitionFile.aspx

All view are rendered with success when I access the page with mobile device. But, they are rendered with wrong layout (AKA masterpage).

I have the following structure: /Views/Shared/Mobile/_Layout.cshtml /Views/Shared/_Layout.cshtml

The problem is, I have to put the following statement in EVERY view:

Layout = "~/Views/Shared/Mobile/_Layout.cshtml";

Is there a place where I can place my logic to render one layout on another one?

if (normalAccess) render normal _Layout.cshtml else (mobileAccess) render /Mobile/_Layout.cshtml

I couldn't find where.

Thanks for any help.

回答1:

There a good article at http://weblogs.asp.net/scottgu/archive/2010/10/22/asp-net-mvc-3-layouts.aspx

You can apparently create a file in your \Views folder called _ViewStart.cshtml where you can put your layout logic to be used by all views

The sample _ViewStart.cshtml is simply:

@{
    Layout = "~/Views/Shared/SiteLayout.cshtml";
}

The article also states: 'Because the _ViewStart.cshtml allows us to write code, we can optionally make our Layout selection logic richer than just a basic property set. For example: we could vary the Layout template that we use depending on what type of device is accessing the site – and have a phone or tablet optimized layout for those devices, and a desktop optimized layout for PCs/Laptops.'

It might take you some playing around with to get this working, I don't have a 2010 install handy to try this however.