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

ASP.NET MVC中为DropDownListFor设置选中项的方法的更多相关文章

  1. MVC 中@Html.DropDownListFor() 设置选中项 这么不好使 ? [问题点数:40分,结帖人lkf181]

    http://bbs.csdn.net/topics/390867060 由于不知道错误原因在哪 我尽量把代码都贴出来吧:重点是:在 Controller 类里 我给 SelectListItem集合 ...

  2. ASP.NET MVC中的Session设置

    最近在ASP.NET MVC项目中碰到这样的情况:在一个controller中设置了Session,但在另一个controller的构造函数中无法获取该Session,会报"System.N ...

  3. 为Asp.net MVC中的RenderSection设置默认内容

    1. RenderSection的简单介绍 Asp.net MVC中提供了RenderSection方法,这样就能够在Layout中定义一些区块,这些区块留给使用Layout的view来实现比如我们定 ...

  4. ASP.NET MVC中MaxLength特性设置无效

    在ASP.NET MVC项目中,给某个Model打上了MaxLength特性如下: public class SomeClass { [MaxLength(16, ErrorMessage = &qu ...

  5. MVC中导航菜单,选中项的高亮问题。

      这个菜单是放在母板页的.比如当前选中的是异常业务监控.如果页面刷新了.就会变成第一张图..选择其他的选项也会,因为页面会刷新嘛.. 怎么处理这个问题了? 答案是记录当前页面的url. 有两种解决思 ...

  6. MVC中导航菜单,选中项的高亮问题。。

    先上图:             这个菜单是放在母板页的.比如当前选中的是异常业务监控.如果页面刷新了.就会变成第一张图..选择其他的选项也会,因为页面会刷新嘛.. 怎么处理这个问题了? 答案是记录当 ...

  7. 在ASP.NET MVC中验证checkbox 必须选中 (Validation of required checkbox in Asp.Net MVC)

    转载自 http://blog.degree.no/2012/03/validation-of-required-checkbox-in-asp-net-mvc/ Why would you want ...

  8. [转]ASP.NET MVC中你必须知道的13个扩展点

    本文转自:http://www.cnblogs.com/ejiyuan/archive/2010/03/09/1681442.html ScottGu在其最新的博文中推荐了Simone Chiaret ...

  9. ASP.NET MVC中你必须知道的13个扩展点

         ScottGu在其最新的博文中推荐了Simone Chiaretta的文章13 ASP.NET MVC extensibility points you have to know,该文章为我 ...

随机推荐

  1. nginx+tomcat实现简单的负载均衡

    host1:10.0.0.10(部署nginx和tomcat) host2:10.0.0.11(部署tomcat) 平台环境(2主机一样) [root@smp ~]# uname -r3.10.0-8 ...

  2. ARM Linux 3.x的设备树(Device Tree)(转)

    http://blog.csdn.net/21cnbao/article/details/8457546

  3. manjaro xfce 18.0 踩坑记录

    manjaro xfce 18.0 踩坑记录 1 简介1.1 Manjaro Linux1.2 开发桌面环境2 自动打开 NumLock3 系统快照3.1 安装timeshift3.2 使用times ...

  4. C#中的ComboBox实现只能选择不能输入,且下拉框中有默认值。

    下拉框有DropDownStyle这一属性,把DropDownStyle类型选为DropDownList,则下拉框只能选择不能输入了.但是这时的下拉框是没有默认值的,即使在Text属性中输入默认值,也 ...

  5. 【转】windows下nginx+mono+fastCGI部署asp.net网站

    原文链接:http://www.cnblogs.com/amityat/archive/2011/08/23/2150153.html 1,什么是nginx 简介Nginx ("engine ...

  6. 软件测试人员遇到发现的bug不能重现怎么办?

    软件测试人员遇到发现的bug不能重现怎么办?   刚刚进入测试的童鞋们,想必都遇到过提出的bug,开发要求重现之后,但是在系统上已经重现不了的情况吧. 那么碰到这样的情况,不管开发还是测试都很纠结,开 ...

  7. BootStrap学习01框架搭建

    中文文档:https://v3.bootcss.com/css/ 开发工具 WebStorm 一.新建项目08bootstrap 引入bootstrap-3.3.7,引入jQuery,引入holder ...

  8. xtu summer individual 2 C - Hometask

    Hometask Time Limit: 2000ms Memory Limit: 262144KB This problem will be judged on CodeForces. Origin ...

  9. CodeForces 632A

    A - Grandma Laura and Apples Time Limit:1000MS     Memory Limit:262144KB     64bit IO Format:%I64d & ...

  10. Linux Bash对拍

    代码: #!/bin/bash while true; do ./rand > input //数据生成器 ./test < input > output //测试程序 ./std ...