gpt4 book ai didi

c# - 在 Razor View 中检查是否为空

转载 作者:行者123 更新时间:2023-11-30 20:27:58 25 4
gpt4 key购买 nike

我将此 View 模型发送到 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; }
}

这是(部分) 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>
}

有时产品类别没有任何产品,这会在我尝试对它们进行计数时导致空引用异常。我该如何检查?

最佳答案

View Models 的一大好处是它们专门为 View 保存数据。我们通常包含额外的只读属性以支持在 View 中更轻松地处理。

例如,在 View 模型中添加如下属性:

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

在 View 中,您只需执行以下操作:

@item.Title (@item.ProductCountInfo)

这使您的 View 保持干净和简单。

编辑

删除了“C#6”版本的属性,无论如何都没有关系

关于c# - 在 Razor View 中检查是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48050632/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com