Reputation: 1602
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?
Upvotes: 3
Views: 4844
Reputation: 5847
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.
Removed "C#6" Version of Property, doesn't matter anyway
Upvotes: 4
Reputation: 13146
Just try like this;
@item.Title (@(item.Products != null ? item.Products.Count.ToString() : "No products"))
or you can use ?.
operator for C# 6
or higher
@item.Title (@(item.Products?.Count.ToString() ?? "No products"))
Upvotes: 3