0

I have a very beginnner's doubt.

Model:

  public class abcModel
  {
    public bool helpMe {get; set;}
  }

View:

  @model abcModel
  <script type="text/javascript">
    $(function () {
        debugger;
        var f = @Model.helpMe
   </script>

Above gives error as True is not defined

But when I do something like this

View

   @model abcModel
  <script type="text/javascript">
    $(function () {
        debugger;
        var f = "@Model.helpMe"
   </script>

Everything seems to be working fine.

Can someone guide me why it's happening. I am beginner in javascript so pardon my ignorance. Why can' I simply assign a boolean variable.

Error:

enter image description here

Unbreakable
  • 7,776
  • 24
  • 90
  • 171
  • `@Model.helpMe`, when stringified, will evalulate to `True`. Your JS then contains `var f = True` which isn't valid. Try `@Json.Encode(Model.helpMe)`, or even `@(Model.helpMe ? "true" : "false")` if you don't have `Json` available. This will result in `var f = true` which is valid. – Scott Jun 02 '17 at 15:59
  • json stuff worked like a charm. Also in chrome developer I can see `var f = true (small case)`. So you mean to say that **javascript** does not understand `True` as boolean but if it is in small case `true` then it understands it. – Unbreakable Jun 02 '17 at 16:10
  • @Scott: Can you put your comment as an answer and kindly tel me the reason too of what I asked in commetn section. Thanks a ton. :) – Unbreakable Jun 02 '17 at 16:11
  • 1
    `True` with an uppercase T means nothing in JavaScript. Also your fix by quoting `"@Model.helpMe"` is not doing what you think. Consider if you used that fix and then in JavaScript you did `if(f){ alert('test'); }`, the alert would fire regardless of the boolean value because the strings `"True"` and `"False"` both evaluate to true. – MrCode Jun 02 '17 at 16:22
  • @MrCode: Just one last doubt. What magic the `@Json.Encode` does. All I know that I need to use `@` when dealing with c sharp code in cshtml file. Please guide me. – Unbreakable Jun 02 '17 at 16:24
  • The JSON encode is converting your c# variable into JSON, which is a way of serializing something into a string with the ability to unserialize it later. As your variable is a boolean the JSON will simply output `true` or `false`. Imagine you wanted to output something more complex like an object with properties, you can do that with JSON encoding. e.g. an object with a property called test and value of 2 would output `{"test":2}`. – MrCode Jun 02 '17 at 17:04
  • Awesome. :) .... – Unbreakable Jun 02 '17 at 17:30

0 Answers0