简体   繁体   中英

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?

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();

});

@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();
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM