【发布时间】:2020-03-05 08:07:21
【问题描述】:
我正在尝试显示一个清单,该清单从 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
}
【问题讨论】:
-
如何调用视图?请在与此视图相关的控制器操作中添加代码。
-
您必须在遍历列表之前进行检查:
@if (Model != null && Model.Amenities != null)。这样,在 get 请求中,您将对模型和 AmenitiesList 进行空检查。 -
鉴于您已标记实体框架,我将假设
BookingRoom和Amenities都来自 ef 查询。我怀疑您在查询BookingRoom时需要Include便利设施,例如var bookings = await context.BookingRooms.Include(x => x.AmenitiesList).ToListAsync()(更多信息在这里-docs.microsoft.com/en-us/ef/ef6/querying/related-data)
标签: c# entity-framework nullreferenceexception