[英]Check for null in razor 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; }
}
這是(部分)視圖:
@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>
}
有時一個產品類別沒有任何產品,當我嘗試對它們進行計數時,這會導致一個空的引用異常。 我該如何檢查?
視圖模型的一大優點是它們保存數據,尤其是用於視圖的數據。 我們通常會包含其他只讀屬性,以支持在View中更輕松地處理。
例如,在視圖模型中添加如下所示的屬性:
public string ProductCountInfo
{
get
{
return Products != null && Products.Any() ? Products.Count().ToString() : "none";
}
}
在視圖中,您只需執行以下操作:
@item.Title (@item.ProductCountInfo)
這樣可以使您的視圖保持簡潔明了。
刪除了屬性的“ C#6”版本,無論如何都沒關系
像這樣嘗試;
@item.Title (@(item.Products != null ? item.Products.Count.ToString() : "No products"))
或者您可以使用?.
C# 6
或更高版本的運算符
@item.Title (@(item.Products?.Count.ToString() ?? "No products"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.