从数据库MVC4下拉列表获取运行时错误

时间:2014-04-07 15:10:25

标签: c# asp.net-mvc-4

我试图在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();
}

2 个答案:

答案 0 :(得分:1)

我会在控制器而不是模型中创建列表。

型号:

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);
}

答案 1 :(得分:0)

我认为您需要将 selectDeparture 字段设为静态,如下所示:

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"))