admin管理员组

文章数量:1289565

I have a list of strings and the following code in 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.

How do I check if model is not null and if my list has values?

I have a list of strings and the following code in 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.

How do I check if model is not null and if my list has values?

Share Improve this question edited May 7, 2013 at 19:04 PSL 124k21 gold badges256 silver badges243 bronze badges asked May 7, 2013 at 18:59 BickBick 18.6k56 gold badges153 silver badges260 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

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.

本文标签: crazorcheck if parameter is null and list has argumentsStack Overflow