首页 > 解决方案 > 如何在 MVC 中使用自定义模型

问题描述

我在 MVC 中创建了一个自定义模型,我将 3 个表项作为列表传递。在视图中,我正在获取这些详细信息。但是在 View 中,我是Object reference not set to an instance of an object. MVC 的新手,任何人都可以帮助我。我不知道我哪里做错了!

我的 MVC 控制器:

public ActionResult Index()
{
   var adminModel = new AdminModel();
   return View(adminModel);
}

我的自定义模型代码:

public class AdminModel
{
    public List<Notification> Notifications { get; set; }            
    public List<Places> Places { get; set; }
}

我的查看代码:

@model TravelFly.Models.AdminModel
@{
    ViewBag.Title = "Admin Dashboard";
    Layout = "~/Views/Shared/_AdminPartial.cshtml";
}
<p class="text-danger">@Model.Notifications.Count</p>
... some other contents...

更新:控制器代码:

public ActionResult Index()
        {
            var adminModel = new AdminModel();
            return View(adminModel);
        }

类文件:

公共列表通知 { get; 放; } = 新列表();公共列表地点{获取;放; } = 新列表();

标签: asp.net-mvc

解决方案


您可能应该初始化模型上的集合或测试视图上是否为空。

var adminModel = new AdminModel
{
   Notifications = new List<Notification>(),
   Places = new List<Places>()
};

或者

@if(Model.Notifications !=null)
{
   <p class="text-danger">@Model.Notifications.Count</p>
}

或者

public class AdminModel
{
    public List<Notification> Notifications { get; set; }            
    public List<Places> Places { get; set; }

   public AdminModel()
   {
      Notifications = new List<Notification>();
      Places = new List<Places>();
   }
}

推荐阅读