9

I have a boolean property in code-behind ASP.NET, now I want to use it in Javascript of mark-up file, but Javascript do not understand True, or False. SO now, I'm using this:

if ( '<%=IsTabVisible%>' == 'True'){
///
}

It works, but quite ugly. Is there a better way to do this?

Thank you

1
  • What does the generated code look like? Commented Jul 28, 2011 at 6:46

1 Answer 1

15

The way I see it you have three options:

A. Do what you are already doing.

B. Perform the if test on the server-side, something like this:

<% if (IsTabVisible) { %>
    // client-side code here, whatever you had inside the brackets
    // of your original if statement
<% } %>

C. Make sure you generate 'true' and 'false' in lowercase so that it will work as client-side JavaScript, something like this:

if (<%= IsTabVisible ? "true" : "false" %>)

Which will appear to the client as:

if (true)

or

if (false)

Option A may look a bit funny but it works fine. Option C produces pretty client-side code that probably nobody will see. My preference is Option B.

Sign up to request clarification or add additional context in comments.

2 Comments

Option C makes Visual Studio complain, a bunch of errors on the page like Syntax error and Expected ')', I think because the Javascript thinks you have an empty if() statement. Did this work at some point and is now broken or what?
@ToastyMallows - Option C uses valid C# which produces valid JavaScript. I haven't used Visual Studio since 2011, but back then it sometimes used to report JS "errors" or warnings for valid JS because it got confused if server-side code was mixed into the JS - but the code would still run.

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.