Reputation: 688
I'm passing in a view model that works with the CheckBoxListFor property and I would like to hide the checkbox section if when I repost to the page there are no check marks ticked. I can show and hide the check box section with no problem using:
$('div.KSearch').hide();
or
$('div.KSearch').show();
What I've been trying to do is check the view model which has a List which hold the information for the keyword model. Is there anyway to check if this list has element being passed in within jquery so that I can show or hide the section with something like:
if (('@Model.SelectedKeywords').length) {
$('div.KSearch').show();
} else {
$('div.KSearch').hide();
}
but this always shows the section. Any ideas?
Upvotes: 0
Views: 14976
Reputation: 317
Check MVC Model is null or not in jquery
<script type="text/javascript">
var checkBoxCount = @(Model.SelectedKeywords != null ? Model.SelectedKeywords.Count : 0);
if (checkBoxCount != 0) {
$('div.KSearch').show();
} else {
$('div.KSearch').hide();
}
</script>
I hope this will help.
Upvotes: 0
Reputation: 5965
Something like this?
var len = @Model.SelectedKeywords.Count;
if (len > 0) {
$('div.KSearch').show();
} else {
$('div.KSearch').hide();
}
('@Model.SelectedKeywords').length
is treated as a string length in javascript, and it's always positive (and true) ;)
Upvotes: 4