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源码,若有不对多有包涵,欢迎指正。

原文地址:https://www.cnblogs.com/zhangyuan0532/p/5099373.html