查看 ASP.NET MVC 2 源代码可以找到一些解决此问题的方法。本质上,SelectList 中的任何 SelectListItem 传递给将 Selected 属性设置为 true 的辅助扩展方法不会与使用应用于项目的 selected 属性呈现的 <option> 元素有任何关系。
<option> 元素上的selected 属性由
确定
1) 检查辅助扩展方法是否传递了SelectList。如果为空,框架将在 ViewData 中查找与键对应的值,该键是您希望为其呈现下拉列表的视图模型属性。如果值为SelectList,则这将用于呈现<select>,包括获取任何选定的值,只要模型属性的模型状态为空。
2) 如果在辅助扩展方法中传递了SelectList 并且模型属性的模型状态为空,则框架将在 ViewData 中查找默认值,使用模型属性名称作为键。视图数据中的值被转换为字符串,并且SelectList 中的任何项传递给辅助扩展方法的值(如果未设置值,则将检查文本)与默认值匹配将具有Selected 属性设置为 true,这反过来将呈现一个带有属性 selected="selected" 的 <option>。
把这些放在一起,我可以看到有两个合理的选项可以选择一个选项并使用强类型 DropDownListFor:
使用以下视图模型
public class CategoriesViewModel
{
public string SelectedCategory { get; private set ; }
public ICollection<string> Categories { get; private set; }
public CategoriesViewModel(string selectedCategory, ICollection<string> categories)
{
SelectedCategory = selectedCategory;
Categories = categories;
}
}
选项 1
在控制器的 ViewData 中设置一个值,根据用于呈现下拉列表的集合的属性名称来呈现您的视图
控制器动作
public class CategoriesController
{
[HttpGet]
public ViewResult Select()
{
/* some code that gets data from a datasource to populate the view model */
ICollection<string> categories = repository.getCategoriesForUser();
string selectedCategory = repository.getUsersSelectedCategory();
CategoriesViewModel model = new CategoriesViewModel(selectedCategory, categories);
this.ViewData["Categories"] = selectedCategory;
return View(model);
}
[HttpPost]
public ActionResult Select(CategoriesViewModel model)
{
/* some code that does something */
}
}
在强类型视图中
<%: Html.DropDownListFor(m => m.Categories, Model.Categories.Select(c => new SelectListItem { Text = c, Value = c }), new { @class = "my-css-class" }) %>
选项 2
使用所选项目的属性名称呈现下拉列表
控制器动作
public class CategoriesController
{
[HttpGet]
public ViewResult Select()
{
/* some code that gets data from a datasource to populate the view model */
ICollection<string> categories = repository.getCategoriesForUser();
string selectedCategory = repository.getUsersSelectedCategory();
CategoriesViewModel model = new CategoriesViewModel(selectedCategory, categories);
return View(model);
}
[HttpPost]
public ActionResult Select(CategoriesViewModel model)
{
/* some code that does something */
}
}
在强类型视图中
<%: Html.DropDownListFor(m => m.SelectedCategory, Model.Categories.Select(c => new SelectListItem { Text = c, Value = c }), new { @class = "my-css-class" }) %>