【问题标题】:If no data in database then how to show "nodata" message in asp.net core如果数据库中没有数据,那么如何在 asp.net 核心中显示“nodata”消息
【发布时间】: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


【解决方案1】:

可以直接判断返回的模型是否有视图上的数据。可以参考下面修改后的代码。

控制器

            public IActionResult Index()
            {
                var model = new List<ManuItem>();
                try
                {
                    model = manuItemRepository.GetAllManuItem();
                }
                catch (Exception ex)
                {
                    ViewBag.Error = "Somthing was Worng" + ex.Message;
                }
                return View(model);
            }

查看

@if (Model.Count() == 0)
{
    <p>No have any Data</p>
}
else
{
    <p>Have Data</p>
}

【讨论】:

  • 感谢您的帮助。这是正常工作。
猜你喜欢
  • 2016-08-05
  • 1970-01-01
  • 2020-02-19
  • 2020-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多