Reputation: 108
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>
Upvotes: 3
Views: 153
Reputation: 23093
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>
Upvotes: 6