c# - 对象引用未设置为对象的实例。模型为空
问题描述
我正在尝试显示一个清单,该清单从 MySQL 数据库中获取数据并将其显示在视图中,并通过我们是否检查了设施来更新表中每个元素的变量 (IsChecked) 的值(我正在显示一些设施)。视图的模型是 Hotel_5.ViewModel.BookingRoom,其中 BookingRoom 是我使用多个模型创建的自定义模型。我在 Model.AmenitiesList.Count() 遇到了异常。模型为空。
这是我的看法
<div class="form-group">
@for (var i = 0; i < Model.AmenitiesList.Count(); i++)
{
@Html.CheckBoxFor(m => m.AmenitiesList[i].IsChecked, new { @class = "form-control" });
<label>@Model.AmenitiesList[i].amenityType</label>
//If you need to hide any values and get them in your post
@Html.HiddenFor(m => m.AmenitiesList[i].AmenityId)
@Html.HiddenFor(m => m.AmenitiesList[i].AmenityPrice)
}
</div>
这是我的视图模型
public class BookingRoom
{
public Bookings bookings { get; set; }
public Rooms rooms { get; set; }
public List<Amenities> AmenitiesList { get; set; } = new List<Amenities>();
}
这是我的设施模型
public class Amenities
{
[Key]
public int AmenityId { get; set; }
public double AmenityPrice { get; set; }
public AmenityType amenityType { get; set; }
public bool IsChecked { get; set; }
}
public enum AmenityType
{
tv,
wi_fi,
hair_dryer,
help
}
解决方案
查询时你也应该包含它AmenitiesList
,否则它将为空:
在控制器中:
var bookingRoom = context.BookingRooms.Include(b => b.AmenitiesList).FirstOrDefault(b => b.Id == someId);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
请注意,我查询的可能不是您想要的,只是为了演示如何使用Include()
,您还应该添加using Microsoft.EntityFrameworkCore
.
推荐阅读
- sql - 如果group by的任何一行不包含值,则sql选择行
- react-native - 应用程序崩溃时应用程序我启动应用程序并且任何待处理的通知都可用
- javascript - 如何使用 PHP 检索 MySQL 中的表行并使用 Javascript 显示它?
- android-ndk - 找不到本机库
- tensorflow - 如何在 TensorFlow - keras 中为密集选择单位?
- python - 额外继承对执行速度的影响
- java - 动态填充网格布局
- python - 改变 Pyspark DataFrame 的结构
- python - 如何在 Pycharm 上更改 Run 终端的字体
- c# - Nlog 不会在 xml 文件文档中创建 Root 元素,同时在同一文件中为不同的日志级别写入日志