Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for null in razor view

Tags:

c#

razor

I'm sending this viewmodel to a view:

public class ViewModelProductCategory
{
    public int Id { get; set; }
    public int? ParentId { get; set; }
    public string Title { get; set; }
    public int SortOrder { get; set; }
    public IEnumerable<ViewModelProductCategory> Children { get; set; }
    public List<ViewModelProduct> Products { get; set; }
    public List<ViewModelProduct> OrphanProducts { get; set; }
}

This is the (partial) view:

@foreach (var item in Model)
{
    <li>
        @item.Title (@item.Products.Count) // this causes problems if num of products = 0.
        <ul>
            @Html.Partial("_CategoryRecursive.cshtml", item.Children)
        </ul>
    </li>
}

Sometimes a product category don't have any products, and that causes a null reference exeption when I try to count them. How can I check for that?

like image 736
Stian Avatar asked Jan 26 '26 04:01

Stian


1 Answers

A big benefit of View Models is the fact that they hold data especially for the View. We often include additional read-only properties to support easier handling in the View.

Example, in the View Model you add a Property like this:

public string ProductCountInfo
{
    get
    {
        return Products != null && Products.Any() ? Products.Count().ToString() : "none";
    }
}

In the View, you simple do:

@item.Title (@item.ProductCountInfo)

This keeps your View clean and simple.

EDIT

Removed "C#6" Version of Property, doesn't matter anyway

like image 75
thmshd Avatar answered Jan 28 '26 19:01

thmshd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!