Razor - check if a parameter is null and the list has arguments

I have a list of lines and the following code in cshtml

@foreach (string tag in Model.TagsList) { <li>@tag</li> } 

If I call my page without a model, I get the following exception Message = The object reference is not set to the object instance.

How to check if a model is null and if there are values ​​in my list?

+4
source share
1 answer

You can check the following: -

 @if(Model != null && Model.TagsList != null) //NUll check for Model { foreach (string tag in Model.TagsList) { <li>@tag</li> } } 

You do not need to check whether the TagsList values TagsList or not (if they are initialized), if the List empty, it will not throw any errors and will not enter the loop.

+7
source

Source: https://habr.com/ru/post/1479604/


All Articles