C#mvc 3使用select列表中的选定值

我正在研究一个MVC3的Web应用程序。 我需要从应用程序pipe理系统编辑blo时显示的类别列表。 在我的viewmodel我有以下属性为类别select列表项列表定义。

/// <summary> /// The List of categories /// </summary> [Display(Name = "Categorie")] public IEnumerable<SelectListItem> Categories { get; set; } 

下一步,我的控制器包含以下编辑操作,其中从数据库填充selectlistitems的列表。

 public ActionResult Edit(Guid id) { var blogToEdit = _blogService.First(x => x.Id.Equals(id)); var listOfCategories = _categorieService.GetAll(); var selectList = listOfCategories.Select(x =>new SelectListItem{Text = x.Name, Value = x.Id.ToString(), Selected = x.Id.Equals(blogToEdit.Category.Id)}).ToList(); selectList.Insert(0, new SelectListItem{Text = Messages.SelectAnItem, Value = Messages.SelectAnItem}); var viewModel = new BlogModel { BlogId = blogToEdit.Id, Active = blogToEdit.Actief, Content = blogToEdit.Text, Title = blogToEdit.Titel, Categories = selectList //at this point i see the expected item being selected //Categories = new IEnumerable<SelectListItem>(listOfCategories, "Id", "Naam", blogToEdit.CategorieId) }; return View(viewModel); } 

当我在返回视图之前设置一个断点时,我看到select列表按我的预期填充。 所以在这一点上,一切似乎都没有问题。 视图模型是完全正确的。 然后在我看来(我使用剃刀)我有以下两个规则应该为我提供select列表。

 @Html.LabelFor(m => m.Categories) @Html.DropDownListFor(model=>model.Categories, Model.Categories, Model.CategoryId) @Html.ValidationMessageFor(m => m.Categories) 

当我运行代码并打开视图来编辑我的博客时,我可以看到所有正确的数据。 此外,select列表正确呈现,但我想要select的项目失去了它的select。 这怎么可能? 直到viewmodel返回的观点一切都没事。 但是,当我在浏览器中查看网页时,只有select列表没有正确的select。 我在这里错过了什么? 还是做错了?

 @Html.DropDownListFor(model=>model.Categories, Model.Categories, Model.CategoryId) 

在这里你没有正确使用助手的方法。 第一个参数必须是视图模型中的一个属性,它将包含当前选定的值。 它应该是一个标量属性,而不是一个集合。

所以在你的视图模型中,你需要添加这样的属性:

 [Display(Name = "Categorie")] public IEnumerable<SelectListItem> Categories { get; set; } public string SelectedValue { get; set; } 

在你的控制器动作中:

 var selectList = listOfCategories.Select(x => new SelectListItem { Text = x.Name, Value = x.Id.ToString() }).ToList(); var viewModel = new BlogModel { BlogId = blogToEdit.Id, Active = blogToEdit.Actief, Content = blogToEdit.Text, Title = blogToEdit.Titel, Categories = selectList, // this is what sets the selected value SelectedValue = blogToEdit.Category.Id }; 

在你看来简单:

 @Html.DropDownListFor(x => x.SelectedValue, Model.Categories) 

我很确定我以前使用select列表项的selected = true属性效果很好。 我遇到的一个问题是ViewData中的一个冲突的值。