页面导航: 站长工具网络编程ASP.NET实用技巧 → 正文内容 DropDownListFor设置选中项

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

投稿:mdxy-dxy 字体:[增加 减小] 类型:转载
这篇文章主要介绍了ASP.NET MVC中为DropDownListFor设置选中项的方法,需要的朋友可以参考下

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

□ 思路

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

  通过遍历List<SelectListItem>类型对象实例

□ 控制器

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

□ 前台视图显示

@model DomainModel
@Html.DropDownListFor(m => m.SomeProperty,(List<SelectListItem>)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<SelectListItem> selectListItems = new List<SelectListItem>();
//遍历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<Project> 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)
    <input  type="submit" value="查看对应分组列表" />
        }
        <p> 当前项目ID: @ViewData["ruturned"]</p>