Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass a ViewModel boolean to a jquery function?

I'd like a div to show if a ViewModel bool is set to true.

I tried this:

$(function () {
    $("#myDiv").toggle(@Model.IsRequired);
}

But @Model.IsRequired appears as either "True" or "False", rather than "true" or "false".

Any ideas?

like image 992
Merenzo Avatar asked Dec 10 '22 05:12

Merenzo


2 Answers

You can just write @Model.IsRequired.ToString().ToLower().

I don't think there's any better solution (other than your own extension method)

like image 50
SLaks Avatar answered Jan 18 '23 01:01

SLaks


Some alternatives to just lowercasing the string:

Use the ternary operator with actual strings

$(function () {
    $("#myDiv").toggle(@(Model.IsRequired?"true":"false"));
}

or you can output different invocations depending on the value

$(function () {
    @if (Model.Required)
    {
        $("#myDiv").toggle(true);
    }
    else
    {
        $("#myDiv").toggle(false);
    }
}

or combine them

$(function () {
    @(Model.IsRequired
         ?"$('#myDiv').toggle(true);"
         :"$('#myDiv').toggle(false);")
}
like image 41
tvanfosson Avatar answered Jan 18 '23 00:01

tvanfosson