javascript MVC 4 使用 jquery 如何检查模型属性中是否有元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18597024/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 12:31:34  来源:igfitidea点击:

MVC 4 using jquery how to check if the model property has elements in it

javascriptjqueryasp.net-mvc

提问by jbolt

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:

我正在传递一个与 CheckBoxListFor 属性一起使用的视图模型,如果我重新发布到页面时没有勾选复选标记,我想隐藏复选框部分。我可以使用以下方法毫无问题地显示和隐藏复选框部分:

$('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:

我一直在尝试做的是检查视图模型,它有一个包含关键字模型信息的列表。无论如何要检查此列表是否在 jquery 中传入了元素,以便我可以使用以下内容显示或隐藏该部分:

if (('@Model.SelectedKeywords').length) {
    $('div.KSearch').show();
} else {
    $('div.KSearch').hide();
}

but this always shows the section. Any ideas?

但这总是显示该部分。有任何想法吗?

回答by I.G. Pascual

Something like this?

像这样的东西?

var len = @Model.SelectedKeywords.Count;

if (len > 0) {
    $('div.KSearch').show();
} else {
    $('div.KSearch').hide();
}

('@Model.SelectedKeywords').lengthis treated as a string length in javascript, and it's always positive (and true) ;)

('@Model.SelectedKeywords').length在 javascript 中被视为字符串长度,并且它始终为正数(并且为真);)

回答by vishpatel73

Check MVC Model is null or not in jquery

在jquery中检查MVC模型是否为空

<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.

我希望这将有所帮助。