0

for some reason I am getting a syntax error when trying to use Razor syntax to store a model object into a JavaScript var. After researching google it seems that I should be able to do something like this. I am using a script tag in my cshtml to do this (I know this is bad practice but I came in late in this project so I'm doing this for uniformity sake) so here is the code.

Index.cshtml:

<script>
    var isAvailable = @Model.IsAvailable; // This gives me a syntax error
</script>

I have a Model class with the Boolean property named IsAvailable and I'm trying to store it in the var isAvailable but Visual Studio doesn't like it. Any idea why?

8
  • What is the exact syntax error? Commented Jul 18, 2016 at 14:22
  • It literally says "Syntax Error", lol. The red error line is right after the semi-colon Commented Jul 18, 2016 at 14:23
  • Your code looks fine to me. Is it showing an error when you run it ? Also, remember True is not true. Commented Jul 18, 2016 at 14:23
  • Is IsAvailable a boolean? Anyway, try to enclose it on quotes: var isAvailable = "@Model.IsAvailable" Commented Jul 18, 2016 at 14:24
  • True is not true. So you should try something liek var isAvailable = @(Model.IsAvailable? "true" : "false"); Commented Jul 18, 2016 at 14:27

2 Answers 2

3

By default MVC calls ToString(), which Booleans converted to string produce upper-cased values (ie. True) where JS boolean syntax requires lower-cased (ie. true). Try this:

var isAvailable = @(Model.IsAvailable.ToString().ToLower());
Sign up to request clarification or add additional context in comments.

1 Comment

If I put single quotes around what is inside the parentheses, then this works perfectly. Thanks!!!
0

Try using this:

<script>
    var isAvailable = @(Model.IsAvailable) ; 
</script>

If not this will surely work:

<script>
    var isAvailable = ('@Model.IsAvailable.ToLower()'=='true'); 
</script>

Comments

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.