MVC3 Razor - Is there a way to change the Layout depending on browser request?

≡放荡痞女 提交于 2019-12-21 17:38:51

问题


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.



来源:https://stackoverflow.com/questions/4303948/mvc3-razor-is-there-a-way-to-change-the-layout-depending-on-browser-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!