Search code examples
c#asp.netasp.net-mvc-4razor

How to check if a list of objects in a model of a view is empty using razor syntax in a HTML page


How should I check the model on a view if it has a list of objects that are not empty using razor syntax in an HTML page?

I need to stop the rendering of the partial view if that list is empty.

while testing and trying to set this up I tried this:

@if (Model.Wealth.WealthList != null)
                {
                    @Html.Partial("_Wealth", Model.Wealth)
                }

But this solution is not working for me.


Solution

  • The empty collection is still a non-null collection, but with zero elements

    Assuming WealthList is a collection, you can use the Any extension method

    @if (Model.Wealth!=null && Model.Wealth.WealthList != null 
                                                    && Model.Wealth.WealthList.Any())
    {
        @Html.Partial("_Wealth", Model.Wealth)
    }
    

    The Any() method will return true if it has at least one item in the collection.

    The Any extension method is defined in the System.Linq namespace which is in the System.Core assembly. Add a reference to it if not already added.