Request.Browser是否始终按预期工作?

时间:2009-07-27 06:26:03

标签: asp.net httpbrowsercapabilities

我有以下代码在“head”中添加正确的CSS文件,具体取决于浏览器,

    string browserName = Request.Browser.Browser;
    string browserVersion = Request.Browser.Version;
    Control Head = Page.Master.FindControl("stuHead");

    if (Head != null)
    {
        if (browserName == "IE")
        {
            if (browserVersion == "6.0")
            {
                Head.Controls.Add(new LiteralControl("<link rel='stylesheet' rev='stylesheet' href='Home-IE6.css' type='text/css' media='all' />"));
            }
            else
            {

                Head.Controls.Add(new LiteralControl("<link rel='stylesheet' rev='stylesheet' href='Home-IE.css' type='text/css' media='all' />"));
            }
        }
        else
        {
            Head.Controls.Add(new LiteralControl("<link rel='stylesheet' rev='stylesheet' href='Home.css' type='text/css' media='all' />"));
        }
    }
    else
    {
        Response.Write("<link rel='stylesheet' rev='stylesheet' href='Home.css' type='text/css' media='all' />");
    }

当我在IE8中打开我的页面时,有时候我会看到Home.css,实际上我应该看到Home-IE.css。我确保Head不是null。不确定是否有人经历过这样的事情。任何评论都赞赏。

1 个答案:

答案 0 :(得分:0)

我想知道你为什么不在HTML部分做这个...有很多网站解释这个css trick

<!--[if IE]>
  <link rel="stylesheet" type="text/css" href="all-ie.css" />
<![endif]-->

<link rel="stylesheet" type="text/css" href="common.css" />

<!--[if IE]>
  <link rel="stylesheet" type="text/css" href="all-ie.css" />
<![endif]-->

<!--[if IE 6]>
  <link rel="stylesheet" type="text/css" href="ie-6.0.css" />
<![endif]-->

<!--[if lt IE 6]>
  <link rel="stylesheet" type="text/css" href="ie-5.0+5.5.css" />
<![endif]-->

只是指出代码中的内容,尝试学习如何重构以及如何重用代码。

string browserName = Request.Browser.Browser;
string browserVersion = Request.Browser.Version;

if (Head != null)
{
    if (browserName == "IE")
    {
        if (browserVersion == "6.0")
            AddCSS("Home-IE6.css", false);
        else
            AddCSS("Home-IE.css", false);
    }
    else
        AddCSS("Home.css", false);
}
else
    AddCSS("Home.css", true);

...

void AddCss(string cssFile, bool write) {
    Control Head = Page.Master.FindControl("stuHead");
    String css = String.Format("<link rel='stylesheet' rev='stylesheet' href='{0}' type='text/css' media='all' />", cssFile);

    if(write)
        Response.Write(css);
    else
        Head.Controls.Add(new LiteralControl(css));
}