1

I'm trying to use a Boolean MVC ViewBag property that is being set in a controller inside of a javascript if statement. However, there is a problem being introduced because the property value gets converted to Pascal case. For example, "true" becomes "True" and "false" becomes "False".

<script type="text/javascript">
    var error = @ViewBag.Dropped;
    if ( error ) {
        $( '#alert-message' ).addClass('alert-success alert-dismissable');
    }
</script>

How can I ensure that the property gets converted to lowercase. I've tried to use javascript function .toLowerCase() and was unsuccessful.

  • You need to consider whether the property is a string or boolean value. The True value is probably actually a boolean (hence the case) and it gets converted to a string when you assign it in Javascript. – Paul Coldrey Sep 17 '15 at 22:33
  • It has nothing to do with upper or lower case. `var error = @ViewBag.Dropped;` returns a text value so `if ( error ) {` will always be evaluated as true - you need `if (error === 'True') {` –  Sep 17 '15 at 22:36
  • use @Json.Encode(ViewBag.Dropped), it worked for me. I was using bool prop from CS file in JS. – Raj Aug 05 '16 at 09:46

4 Answers4

5

One way would be:

<script type="text/javascript">
    var error = @(ViewBag.Dropped ? "true" : "false");
    if ( error ) {
        $( '#alert-message' ).addClass('alert-success alert-dismissable');
    }
</script>
Amit
  • 45,440
  • 9
  • 78
  • 110
3
var error = @ViewBag.Dropped.ToString().ToLower();
Biff MaGriff
  • 8,102
  • 9
  • 61
  • 98
1

I don't think the above answer will work since all strings are true in Javascript,.. you might want

<script type="text/javascript">
    var error = @(ViewBag.Dropped ? true : false);
    if ( error ) {
        $( '#alert-message' ).addClass('alert-success alert-dismissable');
    }
</script>

note if you quote true and false they become strings and true is NOT the same as "true".

Paul Coldrey
  • 1,389
  • 11
  • 20
  • You probably didn't understand my answer (that you're referring to). The string is server side (asp, razor...) it gets evaluated and written to the client side without the quotes. – Amit Sep 17 '15 at 22:40
  • mea culpa - I should have looked more closely :-) – Paul Coldrey Sep 17 '15 at 22:53
0

I use this method all the time because the longer version (value.ToString().ToLowerInvariant()) is too tedious to type all the time:

Add a class to your project or library:

public static class ExtensionMethods
{
    public static string ToJS(this bool value)
    {
        return value.ToString().ToLowerInvariant();
    }
}

then in your js:

<script type="text/javascript">
    var error = @ViewBag.Dropped.ToJS();
    if ( error ) {
        $( '#alert-message' ).addClass('alert-success alert-dismissable');
    }
</script>
freedomn-m
  • 27,664
  • 8
  • 35
  • 57