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?
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?
Share Improve this question asked Sep 3, 2013 at 16:19 jboltjbolt 6883 gold badges16 silver badges37 bronze badges 3- bit confused..post your related HTML codes too.. – bipen Commented Sep 3, 2013 at 16:21
-
1
It looks like you're mixing C# with Javascript.
.length
is the method to check the length of an array in Javascript. If you have a C#List
then you would call.Count
. – Justin Helgerson Commented Sep 3, 2013 at 16:22 -
I tried the
.Count
before I tried the.length
and that throws a null exception on Post if no check boxes were ticked which means I would have to check if the model exists first which gets me back to my original problem – jbolt Commented Sep 3, 2013 at 16:44
2 Answers
Reset to default 4Something 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) ;)
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.