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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With