获得价值不能为空。参数名称:items,MVC4 selectList错误?

时间:2014-04-07 19:23:25

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

我最近有下拉列表工作,一切都很好,但由于某种原因它现在抛出值不能为null异常。我已经交换了变量名称和尝试解决错误的事情,但没有效果。你能不能看看我的代码并指出我正确的方向。我是MVC4的初学者,并且已经在这个问题上工作了好几个小时,所以任何帮助都会受到赞赏。我事先已经发布了相关代码。

编辑:它在视图中的@ Html.DropDownListFor(....)行开头抛出错误

型号:

public partial class SiteBookingsTable
{        
    public string departureAirport { get; set; }
    public string arrivalAirport { get; set; }        

    [Required]
    [Display(Name = "Flying From")]
    public string chooseDepartureAirport { get; set; }

    [Required]
    [Display(Name = "Flying To")]
    public string chooseArrivalAirport { get; set; }
}

查看:

@model Project56.Models.SiteBookingsTable
@{
List<Project56.Models.SiteBookingsTable> selectDepFlight = ViewBag.depList;
}

<tr>
    <td>@Html.LabelFor(model => model.chooseDepartureAirport)<br /> 
       @Html.DropDownListFor(model => model.chooseDepartureAirport, new SelectList(selectDepFlight,"departureAirport","departureAirport"))</td>                    
</tr>

控制器:

    public ActionResult Create()
    {
        List<SiteBookingsTable> selectDepFlight = new List<SiteBookingsTable>();

        selectDepFlight.Add(new SiteBookingsTable() { listID = 0, departureAirport = "-Select-" });
        selectDepFlight.Add(new SiteBookingsTable() { listID = 1, departureAirport = "London (LTN)" });
        selectDepFlight.Add(new SiteBookingsTable() { listID = 2, departureAirport = "Manchester (MAN)" });

        ViewBag.depList = selectDepFlight;


        return View();
    }

    [HttpPost]
    public ActionResult Create(SiteBookingsTable aBooking)
    {
        if (ModelState.IsValid == true)
        {
            newBooking.SiteBookingsTables.Add(aBooking);
            newBooking.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(aBooking);
    }

2 个答案:

答案 0 :(得分:0)

在您的视图中

您正在使用SelectList(selectDepFlight,

但您发送的是ViewBag变量ViewBag.depList = selectDepFlight;

你想要SelectList(ViewBag.depList,

虽然老实说它应该在模型中,而不是ViewBag

答案 1 :(得分:0)

如果我没记错的话,SelectList类型必须是可枚举的。 - Source

**编辑,最好从控制器端而不是在View本身中将值作为可枚举值返回。还要考虑使用ViewModels而不是模型本身。

List<Project56.Models.SiteBookingsTable> selectDepFlight = ViewBag.depList;

//Add the following line(s) to cast your list to an enumerable.

IEnumerable<Project56.Models.SiteBookingsTable> enumSelectDepFlight = selectDepFlight.AsEnumerable<Project56.Models.SiteBookingsTable>

//Alter the following code 
@Html.DropDownListFor(model => model.chooseDepartureAirport, new SelectList(selectDepFlight,"departureAirport","departureAirport"))

//to match the enumerable above

@Html.DropDownListFor(model => model.chooseDepartureAirport, new SelectList(enumSelectDepFlight,"departureAirport","departureAirport"))