我曾多次读过MVC的专家说如果我使用SelectList,最好在我的模型中定义一个IEnumerable<SelectList>
。
例如,在这个question。
考虑这个简单的例子:
public class Car()
{
public string MyBrand { get; set; }
public IEnumerable<SelectListItem> CarBrands { get; set; } // Sorry, mistyped, it shoudl be SelectListItem rather than CarBrand
}
在Controller中,人们会做:
public ActionResult Index()
{
var c = new Car
{
CarBrands = new List<CarBrand>
{
// And here goes all the options..
}
}
return View(c);
}
但是,从Pro ASP.NET MVC,我学习了创建新实例的方法。
public ActionResult Create() // Get
{
return View()
}
[HttpPost]
public ActionResult Create(Car c)
{
if(ModelState.IsValid) // Then add it to database
}
我的问题是:我应该如何将SelectList
传递给View?因为在Get方法中没有模型存在,所以我似乎无法做到这一点。
我当然可以使用ViewBag
来做,但我被告知要避免使用ViewBag
,因为它会导致问题。我想知道我的选择是什么。
您可以创建一个ViewModel,它具有您在表单上所需的Car的所有属性,然后使您的SelectList成为该ViewModel类的属性
public class AddCarViewModel
{
public int CarName { get; set; }
public string CarModel { get; set; }
... etc
public SelectList MyList
{
get;
set;
}
}
你的控制器看起来像
public ActionResult Create() // Get
{
AddCarViewModel model = new AddCarViewModel();
return View(model)
}
[HttpPost]
public ActionResult Create(AddCarViewModel c)
{
if(ModelState.IsValid) // Then add it to database
}
标记
@Html.DropDownListFor(@model => model.ListProperty, Model.MyList, ....)
简单来说,这是我的代码没有模型的副本
在控制器中
ViewBag.poste_id = new SelectList(db.Postes, "Id", "designation");
在视图中
@Html.DropDownList("poste_id", null," -- ", htmlAttributes: new { @class = "form-control" })