user1260827
user1260827

Reputation: 1520

Model's property in javascript code

I have the following javascript code:

$(window).bind("scheduleComplete", (function (event, params) {

    var hallCount = "@Model.EventSchedules.Actual().Hall.Levels.Count";
    var level; 
    //other code

}));

I want to bind only when if statement is true:

if("@Model.EventSchedules.Count" !== "0")
{
 $(window).bind("scheduleComplete", (function (event, params) {

        var hallCount = "@Model.EventSchedules.Actual().Hall.Levels.Count";
        var level; 
        //other code

    }));
}

Model.EventSchedules.Count equals 0, but code inside it runs anyway.
Where is a problem?

Thanks.

Upvotes: 1

Views: 233

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039508

I would recommend you an alternative approach:

<script type="text/javascript">
    var count = @Html.Raw(Json.Encode(Model.EventSchedules.Actual().Hall.Levels.Count));
    if(count > 0) {
        $(window).bind("scheduleComplete", (function (event, params) {
            //other code
        }));
    }
</script>

will render as:

<script type="text/javascript">
    var count = 5;
    if(count > 0) {
        $(window).bind("scheduleComplete", (function (event, params) {
            //other code
        }));
    }
</script>

Upvotes: 1

Kim R
Kim R

Reputation: 561

You are using the !== operator which will need an exact match. If you use != it will use type coercion which will probably make it work. If it does, you know that there is a typing issue. Maybe try without the quotes and work from there.

You could also do the check at the server side and only output the JS if you need it.

Upvotes: 0

Related Questions