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

2025-05-29 0 109

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

思路

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

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

控制器

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24
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

?

1

2

3

4

5

6
public class Department

{

public int Id {get;set;}

public string Name {get;set;}

public bool IsSelected {get;set;}

}

控制器

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19
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();

}

下面是其它网友的补充:

后台代码:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14
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>

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 ASP.NET MVC中为DropDownListFor设置选中项的方法 https://www.kuaiidc.com/102859.html

相关文章

发表评论
暂无评论