在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>
相关文章
猜你喜欢
- 个人服务器网站搭建:如何选择合适的服务器提供商? 2025-06-10
- ASP.NET自助建站系统中如何实现多语言支持? 2025-06-10
- 64M VPS建站:如何选择最适合的网站建设平台? 2025-06-10
- ASP.NET本地开发时常见的配置错误及解决方法? 2025-06-10
- ASP.NET自助建站系统的数据库备份与恢复操作指南 2025-06-10
TA的动态
- 2025-07-10 怎样使用阿里云的安全工具进行服务器漏洞扫描和修复?
- 2025-07-10 怎样使用命令行工具优化Linux云服务器的Ping性能?
- 2025-07-10 怎样使用Xshell连接华为云服务器,实现高效远程管理?
- 2025-07-10 怎样利用云服务器D盘搭建稳定、高效的网站托管环境?
- 2025-07-10 怎样使用阿里云的安全组功能来增强服务器防火墙的安全性?
快网idc优惠网
QQ交流群
您的支持,是我们最大的动力!
热门文章
-
2025-05-29 57
-
2025-05-27 34
-
2025-05-27 59
-
2025-06-04 93
-
2025-06-04 91
热门评论

