1

I have a JavaScript Variable that is set in my ASP.NET page as follows

<script type="text/javascript>
var MyVarable = <%=ASPNETVarable%>;
$(document).ready(function () {
  alert(MyVarable);
}
</script>

Now this is simplified and on the back end code ASPNETVarable is set as

protected string ASPNETVarable="My Backend Value";

The page loads & runs correctly, but in Visual Studio the line

 var MyVarable = <%=ASPNETVarable%>;

Shows that it's a "Syntax error", while it works, how do I remove this "syntax error" ?

1
  • I'm facing the same problem when I build a JavaScript function in a user control. Because the control can be used several times, I use function myFunction_<%= this.ClientID %>() { [...] } to make the function name unique for the control itself. Basically, this error appears on all cases where you do not wrap your variable between ' or ". However everything compiles and runs fine as desired. Annoying error. Commented Aug 14, 2014 at 6:14

1 Answer 1

2

Try the following

var MyVarable = '<%=ASPNETVarable%>';
Sign up to request clarification or add additional context in comments.

2 Comments

Yes that Removes the Syntax Error, but also changes the value, causing issues with the rest of the code (Jason Data)
While this is good for string values it will not work for number variables, or other cases. For instance I want to perform specific javascript, only when a boolean is set in my code-behind. So I do if(<%= Convert.ToInt32(this.IsRequired) %>) [...] that causes the same "Syntax Error" problem.

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.