我一直在瀏覽源代碼ASP.NET MVC 4
,並發現一些有趣的事情,可能會幫助你。 這只是我的想法,我還沒有測試過!
我們必須從內置功能中自定義幾件事情。
查找來自不同文件夾的移動視圖。
只有當url包含移動時,才能呈現移動版本。
我們必須擴展DefaultDisplayMode
類,以從我們的自定義文件夾中選擇移動視圖。 DefaultDisplayMode
在System.Web.WebPages
程序集中。 TransformPath
方法的基本實現將virtualPath
從/Views/Home/Index.cshtml
轉換爲/Views/Home/Index.Mobile.cshtml
。
我們必須重寫TransformPath
方法,該方法會將通過的virtualPath
更改爲ex。從/Views/Home/Index.cshtml
到/Views/MobileHome/Index.cshtml
。
public class CustomDisplayMode: DefaultDisplayMode
{
// ...
protected override string TransformPath(string virtualPath, string suffix)
{
if (String.IsNullOrEmpty(suffix))
{
return virtualPath;
}
// TO DO: modify the virtual path
// for ex. from /Views/Home/Index.cshtml to /Views/MobileHome/Index.cshtml
return virtualPath;
}
}
我們必須從Application
_Start設置我們CustomDisplayMode
到DisplayModeProvider
。我們可以設置ContextCondition
,以便考慮URL。
DisplayModeProvider.Instance.Modes.Insert(0, new CustomDefaultDisplayMode("Mobile")
{
ContextCondition = (context => context.GetOverriddenBrowser().IsMobileDevice
&& check context.Request.Url contains the Mobile segment)
});
爲什麼你需要* mobile *和* web *的不同地址? – VJAI 2012-07-25 13:58:02