我在控制器中有以下代码:
public ActionResult method(int? id){
var list;
var project;
if(id.HasValue){
list = repository.FindAsync(Identity.User.Id);
project = list.FirstOrDefault(p => p.Id == id);
ViewBag.List = list;
ViewBag.SelectedValue = project.Id;
}
return View();
}
我在视图中有这个
<div>
@Html.DropDownList("projectLists", ViewBag.list as List<SelectListItem>, new { @class = "class"})
</div>
如何使用ViewBag.SelectedValue呈现具有该id的项目的下拉列表。我需要一些帮助,因为我是ASP.NET MVC的新手
答案 0 :(得分:2)
将其设为DropDownListFor,并在模型上使用SelectedItemID属性将其发布到。
答案 1 :(得分:0)
您需要从视图模型开始,以表示您想要显示/编辑的内容
public class MyViewModel
{
public int SelectedProject { get; set; }
public SelectList ProjectList { get; set; }
}
然后在GET方法中
public ActionResult method(int? id)
{
IEnumerable<Project> projects = repository.FindAsync(Identity.User.Id);
MyViewModel model = new MyViewModel()
{
SelectedProject = projects.FirstOrDefault(p => p.Id == id),
ProjectList = new SelectList(projects, "Id", "Name")
};
return View(model);
}
在视图中(注意SelectedProject
的值是否与选项的某个值匹配,那么在渲染视图时将选择该选项)
@model yourAssembly.MyViewModel
@using (Html.BeginForm())
{
@Html.DropDownListFor(m => m.SelectedProject, Model.ProjectList, "-Please select-", new { @class = "class" })
<input type="submit" ../>
}
和POST方法
public ActionResult method(MyViewModel model)
{
// model.SelectedProject contains the ID of the selected project
}