开发者

In asp.net mvc, how do I switch the masterpage from the view?

I have been reading this link from Steven Sanderson about mobile web development http://www.asp.net/learn/whitepapers/add-mobile-pages-to-your-aspnet-web-forms-mvc-application, and I am trying to execute his razor code in asp开发者_运维技巧x.

Razor code from url:

@{ 
    Layout = Request.Browser.IsMobileDevice ? "~/Views/Shared/_LayoutMobile.cshtml" 
                                            : "~/Views/Shared/_Layout.cshtml"; 
}

My aspx adaptation:

<%@ Page Title="" Language="C#" MasterPageFile=Request.Browser.IsMobileDevice ? "~/Views/Shared/mobile.Master" : "~/Views/Shared/site.Master" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

but this gives me this error:

ASP.NET runtime error: Only Content controls are allowed directly in a content page that contains Content controls.

Is there a way to do this in aspx?


The answer is one should not change the masterpage from the view. The controller should handle that.

Syntactically, the <@% Page > declaration isn't standard asp.net code and it won't be interpreted correctly, the error you get is probably because it is loading a nonexistent masterpage. But remember that statement is merely a design-time feature.

What you need to do is this:

  • Develop your view against a masterpage.
  • Build your 2nd masterpage, make sure to use the EXACT same names for any <asp:ContentPlaceholders> involved.
  • In the controller method that handles this, swap the masterpage. Perhaps a better way would be to build an attribute which inspects the request for whatever criteria, such as Request.IsMobile, and injects the correct master page. You can inject the masterpage using the ViewResult's MasterPage property.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜