您可以从为移动浏览器创建 MasterPage ( ~/Views/Shared/Site.Mobile.Master
) 开始:
<%@ Master Language="C#" Inherits="System.Web.Mvc.ViewMasterPage" %>
<!DOCTYPE html>
<html lang="en">
<head runat="server">
<meta charset="utf-8" />
<title></title>
</head>
<body>
This is the mobile master page
<asp:ContentPlaceHolder ID="MainContent" runat="server" />
</body>
</html>
然后有~/Views/Home/Index.Mobile.aspx
一个将使用此母版页的移动视图 ( ):
<%@ Page
Language="C#"
MasterPageFile="~/Views/Shared/Site.Mobile.Master"
Inherits="System.Web.Mvc.ViewPage"
%>
<asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
This is the mobile view
</asp:Content>
好的,现在剩下的就是在你的 : 中插入显示模式Application_Start
:
Func<HttpContextBase, bool> contextCheckDelegate = ctx =>
{
// Here you could use the ctx variable which represents the HttpContextBase
// in order to test the UserAgent of the Request and decide whether it is coming
// from a mobile device or not and return true or false respectively which is what
// will determine if your .Mobile masterpage and view will be used for this request
if (IsMobile)
{
return true;
}
return false;
};
DefaultDisplayMode mobileMode = new DefaultDisplayMode("Mobile");
mobileMode.ContextCondition = contextCheckDelegate;
DisplayModeProvider.Instance.Modes.Insert(0, mobileMode);
您当然可以拥有更具体的移动视图,例如 iPhone、iPad ……您只需要调整委托内部使用的条件,即检查用户代理。