tshoemake
tshoemake

Reputation: 1351

Using razor syntax in javascript

This is the code I have. I basically want to look at my model and see if anything exists. Using ternary operator to show or hide based on existence.

$(document).ready(function() {
        (@Model.MyProperties.Any()) ? $('#removeall-toggle').show() : $('#removeall-toggle').hide();
    });

I'm getting an error in chrome dev tools that says:

Uncaught ReferenceError: False is not defined

How do i fix this, or is this a better way of accomplishing this?

Upvotes: 1

Views: 1084

Answers (2)

Shyju
Shyju

Reputation: 218722

Any() method will return True and your code is going to produce the below javascript code when the page is rendered.

$(document).ready(function() {

    (True) ? $('#removeall-toggle').show() : $('#removeall-toggle').hide();
});

Now Javascript will think that True is variable and try to use it's value and it cannot find it as it is not defined earlier in your page. Since this variable is not defined earlier in your page, you are getting the undefined error.

undefined True varibale is not boolean true in javascript. So do a string comparison.

$(document).ready(function() {

    ("@Model.Products.Any()"==="True") ?
                        $('#removeall-toggle').show() : $('#removeall-toggle').hide();

});

Upvotes: 5

StriplingWarrior
StriplingWarrior

Reputation: 156469

@Model.MyProperties.Any() produces a boolean, and when the boolean is output into javascript, you end up with "False" instead of "false". There are a couple of ways to address this.

Approach 1: JSON Serialize

$(document).ready(function() {
    (@JsonConvert.SerializeObject(Model.MyProperties.Any())) ? $('#removeall-toggle').show() : $('#removeall-toggle').hide();
});

Or, a simpler version:

$(document).ready(function() {
    var shouldShow = @JsonConvert.SerializeObject(Model.MyProperties.Any());
    $('#removeall-toggle').toggle(shouldShow);
});

Approach 2: Only output what you need

$(document).ready(function() {
    @if(Model.MyProperties.Any())
    {
       @:$('#removeall-toggle').show();
    }
    else
    {
       @:$('#removeall-toggle').hide();
    }
});

Upvotes: 4

Related Questions