简体   繁体   中英

Using asp.net inline tags in javascript conditional

I got sick of all my jscript social widget/analytics initialization cluttering my debug output while testing my Asp.Net webforms page locally. So I tried this in my HTML markup:

<script>
if (<%= !Request.IsLocal ? "true" : "false" %>) {

This actually emits correct jscript code ("if (true)") with no run-time errors but Visual Studio doesn't like it. I'm getting a syntax error on the closing ')'. Definitely don't like seeing compile errors, even if they're bogus, every darn time I compile.

I changed it to compare strings, like

if ("<%= Request.IsLocal %>" === "False") {

Which works and emits code like 'if ("True" === "False")', but... that just grates on my nerves and looks ugly. Is this just a Visual Studio weirdness, or is there a better way to use asp.net server boolean values in jscript conditionals?

Could you do something like:

<script>
  var isLocal = "<%= Request.IsLocal %>" == "True";
  ...

  if(isLocal) {
    // do local stuff
  }
</script>

VS does not complain.

The combination of javascript/html/css + server tags will show squigly lines depending on their placement etc.

If you truly want to avoid that, you would have to create your javascript in the code behind.

<asp:Literal id="script" runat="server">

And in the code behind.

if (Request.IsLocal) {
    script.Text = "<script>function(){}</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