Asp.net mvc 4 ASP.NET MVC填充dropdownlist

Asp.net mvc 4 ASP.NET MVC填充dropdownlist,asp.net-mvc-4,drop-down-menu,Asp.net Mvc 4,Drop Down Menu,我已经尝试填充dropdownlist一段时间了,希望能得到一些帮助。我有我的模型和视图模型,我正在尝试填充Dropdownlist并将其发送到视图,以便用户可以选择一个cartype并单击submit public class Cars { public int CarId { get; set; } public string Name { get; set; } } public class CarViewModel { public int SelectedCa

我已经尝试填充dropdownlist一段时间了,希望能得到一些帮助。我有我的模型和视图模型,我正在尝试填充Dropdownlist并将其发送到视图,以便用户可以选择一个cartype并单击submit

public class Cars
{
    public int CarId { get; set; }
    public string Name { get; set; }
}

public class CarViewModel
{
    public int SelectedCarId { get; set; }
    public IEnumerable<SelectListItem> CarTypes;

}

public ActionResult FillDropDown()
{
     var model = new ViewModel();
     model.CarTypes = (from s in context.CarTypes
                      select new SelectListItem()
                      {
                         Text = s.Name,
                         Value = SqlFunctions.StringConvert((double)s.Id).Trim(),
                      }).ToList<SelectListItem>();

    return View(model);
}
因此,我想了解一些如何在视图中渲染此内容的帮助。我尝试了以下操作,但出现了nullreference异常

@Html.BeginForm("FillDropDownList","Home", FormMethod.Post,null)
{
    @Html.DropDownListFor(x => x.SelectedCarId, Model.CarTypes);
    <input type="submit" value="submit" />
}

尝试使用CarViewModel而不是ViewModel

public ActionResult FillDropDown()
{
   var model = new CarViewModel(); //CarViewModel instead of ViewModel
   model.CarTypes = (from s in context.CarTypes
                     select new SelectListItem()
                     {
                        Text = s.Name,
                        Value = SqlFunctions.StringConvert((double)s.Id).Trim(),
                     }).ToList<SelectListItem>();

   return View(model);
}

确保FillDropDown方法中的SelectListItem不为null。

在操作结果中使用“CarViewModel”而不是“ViewModel”。从何处获得异常?语境从何而来?它是空的吗?Model.CarTypes甚至Model是否为null?当我将它发送到视图:return Viewmodel时,我可以看到它填充了正确的数据。但在第行:@Html.DropDownListForx=>x.SelectedCarId,Model.CarTypes;我得到一个nullreference异常,说Model.CarTypes为空。thx!实际上这行代码不起作用:@Html.DropDownListForx=>x.SelectedCarId,Model.CarTypes;我想发回所选的carid。模型中填充了正确的数据。
public class CarViewModel
{
    public int SelectedCarId { get; set; }
    public SelectList CarTypes;
}