zoukankan      html  css  js  c++  java
  • C# mvc DropDownList选中状态无效情况分析

    情况:

    DropDownList控件使用List<SelectListItem>()设置下拉选项和默认值。
    当控件的Name和后台的ViewBag(或ViewData)的Key重复,会导致选中状态无效。

    规则如下
    1、DropDownList数据源可从ViewBag(或ViewData)中同名Key中自动获取
    例如,下面这种写法可自动为控件加下拉选项:
    Controller中:ViewData["MyList"] = new List<SelectListItem>(){...};
    View中:@Html.DropDownList("MyList")//DropDownList无直接数据源

    2、DropDownList数据源优先从DropDownList直接的数据源获取。若DropDownList有直接数据源,则ViewData同名Key值(应该是ViewData[Key] as string)只作为默认选中值(见3)

    如下情况,都使用SelectListItem,类似于1,option为view的,选中为空

    Controller中:ViewData["MyList"] = new List<SelectListItem>(){...};
    View中:@Html.DropDownList("MyList", new List<SelectListItem>(){...})//DropDownList有直接数据源

    3、DropDownList选中值优先从ViewBag(或ViewData)中同名Key中自动获取
    例如,下面这种写法,优先选中的是viewdata中value为"optionvalue"的选项:
    Controller中:ViewData["MyList"] = "optionvalue";
    View中:@Html.DropDownList("MyList", new List<SelectListItem>(){...})

    所以,如上情况,对应的原因同规则2所述,DropDownList优先用了ViewData中的数据作为默认选中值,由于ViewData中的数据dataDic是Dictionary<string,string>类型,DropDownList会认为选中值为(dataDic as string)....后果就是谁都没选中

    以上几个规则都是测试出来的结果,未翻看mvc源码,若有不对多有包涵,欢迎指正。

  • 相关阅读:
    从官网下载mod_jk.so
    一台电脑上运行两个tomcat
    官网下载apache服务器并运行
    给tomcat7w.exe改名字
    运行tomcat7w.exe,提示:指定的服务未安装unable to open the service tomcat7
    一台电脑启动多个tomcat
    Spring和Hibernate结合的一个小例子
    spring和jdbc结合的一个小例子
    svn 文件后面显示时间和提交人
    svn 未提交的显示黑色的星*
  • 原文地址:https://www.cnblogs.com/zhangyuan0532/p/5099373.html
Copyright © 2011-2022 走看看