从数据库MVC4获取带有下拉列表的运行时错误
本文关键字:下拉列表 运行时错误 数据库 MVC4 获取 | 更新日期: 2023-09-27 17:57:05
我正试图在MVC4中创建一个下拉列表,该列表源自一个名为"SiteTableBookings"的数据库模型,运行时错误为:
"在App_Web_e3cawdyt.dll中发生类型为System.NullReferenceException的异常,但未在用户代码"中处理
基本上,该应用程序需要一个航班预订的下拉列表,我已经搜索了许多关于如何在线实现下拉列表的方法,但无法运行该应用程序。
MVC4新手,仍在学习任何帮助,将不胜感激。
型号:
public partial class SiteBookingsTable
{
public int listID { get; set; }
public string departureAirport { get; set; }
public string chooseDepartureAirport { get; set; }
public IEnumerable<SiteBookingsTable> selectDeparture = new List<SiteBookingsTable>
{
new SiteBookingsTable {listID = 0, departureAirport = "London (LTN)"},
new SiteBookingsTable {listID = 1, departureAirport = "Manchester (MAN)"}
};
}
视图:
<tr>
<td>@Html.LabelFor(model => model.chooseDepartureAirport)<br />
@Html.DropDownListFor(model => model.chooseDepartureAirport,
new SelectList(Model.selectDeparture, "listID", "departureAirport")) </td>
</tr>
控制器:
public ActionResult Create()
{
return View();
}
我会在控制器而不是模型中创建列表。
型号:
public partial class SiteBookingsTable
{
public int listID { get; set; }
public string departureAirport { get; set; }
public string chooseDepartureAirport { get; set; }
public IEnumerable<SelectListItem> selectDeparture { get; set; }
}
视图:
<tr>
<td>@Html.LabelFor(model => model.chooseDepartureAirport)<br />
@Html.DropDownListFor(model => model.chooseDepartureAirport,
Model.selectDeparture)
</td>
</tr>
控制器:
public ActionResult Create()
{
IEnumerable<SiteBookingsTable> selectDeparture = new List<SiteBookingsTable>()
{
new SiteBookingsTable {listID = 0, departureAirport = "London (LTN)"},
new SiteBookingsTable {listID = 1, departureAirport = "Manchester (MAN)"}
};
model = new SiteBookingsTable()
model.selectDeparture = new SelectList(selectDeparture, "listID", "departureAirport");
return View(model);
}
我认为您需要将selectDepartment字段设置为静态字段,如下所示:
public static IEnumerable<SiteBookingsTable> selectDeparture = new List<SiteBookingsTable>
{
new SiteBookingsTable { listID = 0, departureAirport = "London (LTN)" },
new SiteBookingsTable { listID = 1, departureAirport = "Manchester (MAN)" }
};
然后更新您的下拉列表以使用此静态属性,并指向departureAirport属性:
@Html.DropDownListFor(model => model.departureAirport,
new SelectList(SiteBookingsTable.selectDeparture, "listID", "departureAirport"))