我一直在尝试填充下拉列表一段时间,并希望得到一些帮助。我有我的模型和viewmodel以及我尝试填充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" />
}
答案 0 :(得分:0)
尝试使用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);
}
修改强>
将CarViewModel中的IEnumerable属性更改为SelectList
public class CarViewModel
{
public int SelectedCarId { get; set; }
public SelectList CarTypes;
}
确保FillDropDown()方法中的SelectListItem不为null。