[英]How can I set the selected value of dropdownlist in asp.net mvc 4
I have the following code in the controller: 我在控制器中有以下代码:
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();
}
And I have this in the view 我认为这是
<div>
@Html.DropDownList("projectLists", ViewBag.list as List<SelectListItem>, new { @class = "class"})
</div>
How can I use the ViewBag.SelectedValue to render the dropdown with the project that have that id. 如何使用ViewBag.SelectedValue渲染具有该ID的项目的下拉列表。 I need a little help for this because I am new in ASP.NET MVC
我需要一点帮助,因为我是ASP.NET MVC的新手
将其设为DropDownListFor,并在其模型上具有SelectedItemID属性以将其发布到。
You need to start with a view model to represent what you want to display/edit 您需要从一个视图模型开始,以代表您想要显示/编辑的内容
public class MyViewModel
{
public int SelectedProject { get; set; }
public SelectList ProjectList { get; set; }
}
Then in the GET method 然后在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);
}
And in the view (note if the value of SelectedProject
matches one of the values of the options, then that option will be selected when the view is rendered) 并且在视图中(请注意,如果
SelectedProject
的值与选项的值之一匹配,则在呈现视图时将选择该选项)
@model yourAssembly.MyViewModel
@using (Html.BeginForm())
{
@Html.DropDownListFor(m => m.SelectedProject, Model.ProjectList, "-Please select-", new { @class = "class" })
<input type="submit" ../>
}
and the POST method 和POST方法
public ActionResult method(MyViewModel model)
{
// model.SelectedProject contains the ID of the selected project
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.