Detecting IE11 in Razor

I've always detected IE and their respective versions using HTML conditional statements and that worked pretty well for me. I'd use the conditions to apply a class to the <html> element so I could use that in my CSS and pick it up with my jQuery code. But then IE10 came out and the conditions don't actually register that you're using Internet Explorer. So a hacky piece of JavaScript was required to detect IE10.

<!--[if !IE]><!-->
            if (/*@cc_on!@*/false) { document.documentElement.className += ' ie'; document.documentElement.className += ' ie10'; }

This has worked just fine for me before, as all the Umbraco sites I've developed have been running in WebForms. I've recently started installing Umbraco v6 and v7 (depending on whether the server runs .net 4.5 or not) and utilising the MVC rendering engine. The thing is, the render engine thinks that the @ signs in the script above are Razor scripts and then spits out a server error. I had a hunt about to see if you could escape the @ sign in Razor and discovered that you just typed @@. For some reason this didn't actually work for me, but then I thought, Why don't I just use Razor to detect Internet Explorer?  So I removed my conditional statements and added this script instead:

    var ieClass = "";
    var browser = Request.Browser.Browser;
    var browser_version = Request.Browser.MajorVersion;
    if (browser == "IE") {
        ieClass = "ie";
        if (browser_version < 7) { ieClass="ie lt-ie11 lt-ie10 lt-ie9 lt-ie8 lt-ie7"; }
        else if (browser_version == 7) { ieClass="ie lt-ie11 lt-ie10 lt-ie9 lt-ie8"; }
        else if (browser_version == 8) { ieClass="ie lt-ie11 lt-ie10 lt-ie9"; }
        else if (browser_version == 9) { ieClass="ie lt-ie11 lt-ie10";}
        else if (browser_version == 10) { ieClass="ie lt-ie11";}
    else if (browser == "InternetExplorer"){
        if (browser_version == 11) { ieClass="ie ie11"; }
<html lang="en" class="no-js @ieClass">

For some reason Microsoft decided that their browser will register as InternetExplorer from now on rather than IE, hence the extra condition down the bottom. I store the browser and the version as variables so that they can be used further down the page so that any browser specific markup or scripts can be added. An example would be adding a condition to include json2.js in IE7 and lower to add JSON support to the browser. The benefits of using Razor over HTML conditional statements is that you don't have to serve up the conditions and the markup within to all browsers, cutting down your file sizes and load times ever so slightly. I'm not aware of any issues with using Razor instate of conditional statements, but if you come across any please shoot me an email!

Written by: Ben Meyrick