【发布时间】:2021-06-21 17:50:56
【问题描述】:
如果数据库中没有任何记录,如何在列表视图页面中显示没有任何数据消息。
这是我要注入此控制器的 ICouponRepository 接口。
IEnumerable<ManuItem> GetAllManuItem();
这是我要继承 ICouponRepository 的 SQLManuItemRepository
public IEnumerable<ManuItem> GetAllManuItem()
{
try
{
return context.ManuItems.Include(mi => mi.Category)
.Include(mi => mi.SubCategory)
.Where(mi => mi.IsDelete == false);
}
catch (Exception ex)
{
var exception = ex.Message;
return null;
}
}
这是我的控制器方法
public IActionResult Index()
{
try
{
var model = manuItemRepository.GetAllManuItem();
if (model == null)
{
ViewBag.NoData = "No have any Data";
return View();
}
return View(model);
}
catch (Exception ex)
{
ViewBag.Error = "Somthing was Worng" + ex.Message;
}
return View();
}
此方法或视图有何变化?
【问题讨论】:
-
如果
GetAllManuItem返回项目的集合,那么您可能还需要检查其.Length或.Count属性:if (model == null || model.Count == 0) { ViewBag.NoData = ...... }。此外,如果这是关于 menu items,那么请正确拼写为 Menu Item... -
我明白,代码只是 sn-p,但 GetAllManuItem 中的 try/catch 看起来是多余的并且隐藏了错误。最好允许在父 Index() 中捕获异常以明确报告。
标签: asp.net-mvc asp.net-core asp.net-web-api