asp.net-mvc - 如何在 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; 放; } = 新列表();公共列表地点{获取;放; } = 新列表();
解决方案
您可能应该初始化模型上的集合或测试视图上是否为空。
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>();
}
}
推荐阅读
- c# - 如何将对象从屏幕外移动到屏幕外?(Unity2D)
- java - Spring Boot - 将应用程序属性注入 Util 类变量
- apache - HTTP缓存问题。请求开启和关闭
- mysql - 在 MySQL SUB-QUERY 中尊重 GROUP BY 子句
- python - 如何从python的崩溃转储中获取信息
- python - Groupby 并将多个 lambda 函数应用于 Pandas DataFrame
- http - MFC 中的原始 http 消息头
- android - Admob 广告不适用于 android,但可以在统一编辑器中使用
- c - 从 char * 转换为其他兼容对齐的指针类型是否在 C89 中定义了行为?
- next.js - 在 tailwind next.js 上跳过 purgecss 的白名单页面