Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

razor - check if parameter is null and list has arguments

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?

like image 915
Bick Avatar asked Feb 17 '23 14:02

Bick


1 Answers

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.

like image 153
PSL Avatar answered Feb 22 '23 16:02

PSL