Internet Explorer 7 + MVC 3 = bad urls?

2019-05-09 21:58发布

问题:

This is weird. I say weird because on IE 8 and above (as well as FF) my urls generated by Html.ActionLink() creates an url in the correct form -> http://mydomain.com/myapp/mycontroller/myaction but on IE 7 and IE8 running in compatibility mode the urls are generated as -> http:///myapp/mycontroller/myaction . This is also affecting anything that uses Url.Content().

This is a concern because I have users still holding on to IE 7 for dear life (I don't get it either). Plus our Active Directory policy has things set for some (not all) users so that IE 8 is forced into compatibility mode and cannot be turned off. It also overrides the compatibility meta tag.

What should I check for here within MVC? Is there a web.config setting I need to look at?

Code: Action links:

@Html.ActionLink("My Text", "Action", "Controller", new { Param1 = Model.Param1 }, new { @class = "linkButton" })

Url.Content:
Url.Content("~/Content/openHS.png")

Update: I found a similar item dealing with this issue in PHP: Why can't I use relative URLs with IE7?

A couple of other articles around the web mentioned using the <base> header tag.. trying this now. used the search "relative urls" "Internet explorer 7"

回答1:

This works. I tested in WinXP mode with IE 8 in compatibility mode as well as in Internet Explorer 8 IE 7 mode, IE 9, IE9 Compat, FF 11. No harm to my existing JavaScript

For Razor:

@{
     string baseHref;

     if(this.Request.Browser.Type == "IE7" && !this.Request.UserAgent.Contains("Trident/5.0"))
     {
          baseHref = this.Request.Url.Scheme + "://" + this.Request.Url.Authority + Url.Content("~");
     }
     else 
     {
          baseHref = Url.Content("~");
     }
}

Then in the top of the <head>:

<meta http-equiv="X-UA-Compatible" content="IE=9;IE=8;" />
<meta charset="utf-8" />
<base href="@(baseHref)"/>

One explanation on the above: Trident/5.0 is IE 9's compatibility engine and seems to allow IE9 to interpret relative links according to the page domain instead of base. I'm sure you can remove the Razor code if you so choose. This was a compatibility patch for me.