ASP.NET MVC中为DropDownListFor设置选中项的方法

这篇文章主要介绍了ASP.NET MVC中为DropDownListFor设置选中项的方法,需要的朋友可以参考下

在MVC中,当涉及到强类型编辑页,如果有select元素,需要根据当前Model的某个属性值,让Select的某项选中。本篇只整理思路,不涉及完整代码。

□ 思路

往前台视图传的类型是List,把SelectListItem选中项的Selected属性设置为true,再把该类型对象实例放到ViewBag,ViewData或Model中传递给前台视图。

  通过遍历List类型对象实例

□ 控制器

 public ActionResult SomeAction(int id) { //从数据库获取Domain Model var domainModel = ModelService.LoadEntities(m => m.ID == id).FirstOrDefault(); //通过某个方法获取List类型对象实例 List items = SomeMethod(); //遍历集合,如果当前Domain model的某个属性与SelectListItem的Value属性相等,把SelectListItem的Selected属性设置为true foreach(SelectListItem item in items) { if(item.Value == Convert.ToString(domainModel.某属性)) { item.Selected = true; } } //把List集合对象实例放到ViewData中 ViewData["somekey"] = items; //可能涉及到把Domain Model转换成View Model return PartialView(domainModel); } 

□ 前台视图显示

@model DomainModel
@Html.DropDownListFor(m => m.SomeProperty,(List)ViewData["somekey"],"==请选择==")

通过遍历Model集合

给View Model设置一个bool类型的字段,描述是否被选中。
把Model的某些属性作为SelectListItem的Text和Value值。根据View Model中的布尔属性判断是否要把SelectListItem的Selected设置为true.

□ View Model

 public class Department { public int Id {get;set;} public string Name {get;set;} public bool IsSelected {get;set;} }

□ 控制器

 public ActionResult Index() { SampleDbContext db = new SampleDbContext(); List selectListItems = new List(); //遍历Department的集合 foreach(Department department in db.Departments) { SelectListItem = new SelectListItem { Text = department.Name, Value = department.Id.ToString(), Selected = department.IsSelected.HasValue ? department.IsSelected.Value : false } selectListItems.Add(selectListItem); } ViewBag.Departments = selectListItems; return View(); }

下面是其它网友的补充:

后台代码:

 public ActionResult Index(FormCollection collection) { IList li = Utility.SqlHelper.getProjectList(); SelectList selec = new SelectList(li, "ID", "Name"); if (collection["drop"] != null) { string projectID = collection["drop"]; selec = new SelectList(li, "ID", "Name", projectID);//根据返回的选中项值设置选中项 ViewData["ruturned"] = collection["drop"]; } ViewData["drop"] = selec; return View(); } 

前端代码:

  @using (Html.BeginForm()){
@Html.DropDownList("drop", ViewData["d"] as SelectList)
   
        }
       

当前项目ID: @ViewData["ruturned"]

以上就是ASP.NET MVC中为DropDownListFor设置选中项的方法的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » ASP编程