【问题标题】:how to display View by browser type in asp.net mvc?如何在 asp.net mvc 中按浏览器类型显示视图?
【发布时间】:2018-05-02 17:23:24
【问题描述】:

我在我的项目中使用了很多css和javascript,仅IE9浏览器不支持,

所以我为所有视图创建了两个版本,第一个版本用于没有 css 和 javascript 的 IE 浏览器,第二个版本用于其他浏览器的所有 css 和 javascript。

如果用户浏览器是 IE9(仅版本 9),则显示第一个视图,否则显示第二个视图。

【问题讨论】:

标签: c# asp.net-mvc internet-explorer-9


【解决方案1】:

您必须在 mvc 中使用 Custom DisplayMode,在浏览器中使用 User-agent。

任何浏览器都有一个唯一的用户代理,Internet Explorer 9 是“MSIE 9”。

如果视图名称是 First.cshtml,

创建名称为:First.IE9.cshtml 的视图

在 global.asax 中

protected void Application_Start(){
//other code

DisplayModeProvider.Instance.Modes.Insert(0,new DefaultDisplayMode("IE9")
{
    ContextCondition=context=> context.request.UserAgent.Contains("MSIE 9")
});
}

【讨论】:

    【解决方案2】:

    在您的控制器中,您可以检查请求的 UserAgent 属性。

    HttpContext.Current.Request.UserAgent

    完整代码示例:

    private const string IEUserAgent = "Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.0; Trident/5.0)";
    
    public ActionResult Index()
    {
        string userAgent = HttpContext.Current.Request.UserAgent;
    
        if (userAgent == IEUserAgent) 
        {
           return View("IE9View");
        }
    
        return View();
    }
    

    您可能希望将 UserAgent 字符串封装在一个常量文件中,该文件将服务于更合适的位置而不是控制器级别。

    另一种方法是在 Global.asax 中使用DisplayModeProvider

    DisplayModeProvider.Instance.Modes.Insert(1, new DefaultDisplayMode("IE9")  
    {  
        ContextCondition = (ctx => ctx.GetOverriddenUserAgent()  
        .IndexOf("MSIE 9", StringComparison.OrdinalIgnoreCase) > 0)     
    });  
    

    然后,您将在应用程序的“视图”部分中创建一个 Index.IE9.cshtml 文件,其中包含要显示给使用 Internet Explorer 9 的用户的标记。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-27
      • 1970-01-01
      • 1970-01-01
      • 2011-03-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多