javascript razor - 检查参数是否为空并且列表是否有参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16426554/
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
razor - check if parameter is null and list has arguments
提问by Bick
I have a list of strings and the following code in cshtml
我在 cshtml 中有一个字符串列表和以下代码
@foreach (string tag in Model.TagsList)
{
<li>@tag</li>
}
If I call my page without model I get the following exception Message=Object reference not set to an instance of an object.
如果我在没有模型的情况下调用我的页面,我会收到以下异常 Message=Object reference not set to an instance of an object。
How do I check if model is not null and if my list has values?
如何检查模型是否不为空以及我的列表是否有值?
回答by PSL
You can check like this:-
你可以这样检查:-
@if(Model != null && Model.TagsList != null) //NUll check for Model
{
foreach (string tag in Model.TagsList)
{
<li>@tag</li>
}
}
You don't need to check if TagsList
has values or not (if initialized) if empty List
it wont throw any error and won't step in to the loop.
您不需要检查是否TagsList
有值(如果已初始化),如果为空,List
则不会抛出任何错误并且不会进入循环。