在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 "htmlcode">
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>
免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件!
如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
白云城资源网 Copyright www.dyhadc.com
暂无“ASP.NET MVC中为DropDownListFor设置选中项的方法”评论...
更新日志
2025年11月14日
2025年11月14日
- 小骆驼-《草原狼2(蓝光CD)》[原抓WAV+CUE]
- 群星《欢迎来到我身边 电影原声专辑》[320K/MP3][105.02MB]
- 群星《欢迎来到我身边 电影原声专辑》[FLAC/分轨][480.9MB]
- 雷婷《梦里蓝天HQⅡ》 2023头版限量编号低速原抓[WAV+CUE][463M]
- 群星《2024好听新歌42》AI调整音效【WAV分轨】
- 王思雨-《思念陪着鸿雁飞》WAV
- 王思雨《喜马拉雅HQ》头版限量编号[WAV+CUE]
- 李健《无时无刻》[WAV+CUE][590M]
- 陈奕迅《酝酿》[WAV分轨][502M]
- 卓依婷《化蝶》2CD[WAV+CUE][1.1G]
- 群星《吉他王(黑胶CD)》[WAV+CUE]
- 齐秦《穿乐(穿越)》[WAV+CUE]
- 发烧珍品《数位CD音响测试-动向效果(九)》【WAV+CUE】
- 邝美云《邝美云精装歌集》[DSF][1.6G]
- 吕方《爱一回伤一回》[WAV+CUE][454M]