简体   繁体   中英

ASP.NET: Set C# variable in JavaScript code

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>

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"; } @{ 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM