razor - check if parameter is null and list has arguments

11,511

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.

Share:
11,511
Bick
Author by

Bick

Updated on June 26, 2022

Comments

  • Bick
    Bick almost 2 years

    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?