3

I am using ASP.NET C# and in my viewsAll.cshtml i have a JavaScript
that detect if the user is using Internet Explorer or not.
the alert("Other Browser"); or the alert("Internet Explorer"); is working fine.

The Problem is both c# code lines will be executet:
@{ Session["BrowserName"] = "IE";} and @{Session["BrowserName"] = "other";}

but in case of i am using Internet Explore it should only execute
@{ Session["BrowserName"] = "IE";}

viewsAll.cshtml:

<script>
 var usera = window.navigator.userAgent;
 var ie = usera.indexOf("IE ");

 if(ie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./))  // If Internet Explorer
 {    
  alert("Internet Explorer");
  $('head').append('<link href="@Url.Content("~")Content/Styles/styleForIE.css" rel="stylesheet" />');
  @{ Session["BrowserName"] = "IE";}
 }
 else{  // If Other Browser
    alert("Other Browser");
    $('head').append('<link href="@Url.Content("~")Content/Styles/styleForOther.css" rel="stylesheet" />');
    @{Session["BrowserName"] = "other";}
}
</script>

1 Answer 1

6

You mixed here the concepts of server-side code and client side-code wrong:
All C# code is always executed on the server-side even if it is inside a client-side conditional block.
This means both of your @{ Session["BrowserName"] = "XX"; } code-blocks are always executed on the server and not only the one appropriate, because both blocks are only "client-side-conditionals" - on the server they are "just text".

What you should/could do is turn the conditional in a server-side evaluation and check the user-agent on the server:

<script>
    @if(Request.UserAgent.Contains("IE ") || new Regex(@"Trident.*rv\:11\.").Match(Request.UserAgent).Success)
    {    
        Session["BrowserName"] = "IE";
        <text>
            alert("Internet Explorer");
            $('head').append('<link href="@Url.Content("~")Content/Styles/styleForIE.css" rel="stylesheet" />');
        </text>
    }
    else
    {
        Session["BrowserName"] = "other";
        <text>
            alert("Other Browser");
            $('head').append('<link href="@Url.Content("~")Content/Styles/styleForOther.css" rel="stylesheet" />');
        </text>
    }
</script>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.