小记:MVC4 显示DropDownListFor时绑定失效

小记:MVC4 显示DropDownListFor时绑定失效
情况描述:
Model里有一个List:SearchMokutekitiResults
该List里有一列数据是cd类型(端末cd),显示时需要以List<SelectListItem>的形式显示出来,并且可以编辑
该列的数据源已封装为List端末
前台使用for遍历,以“DropDownListFor”的形式显示SearchMokutekitiResults里的端末
结果Selected(端末cd)绑定不上

经调查,这属于微软的一个bug
解决方法:
笨办法,手动绑定

@for (int i = 0; i  <  Model .SearchMokutekitiResults.Count; i++)
                {
                    <tr
>
                         < td >< span  style ="width: 80px;" >@{
                                                            List < SelectListItem > list = new List < SelectListItem >(Model.List端末);
                                                            for (int j = 0; j  <  list .Count; j++)
                                                            {
                                                                list[j].Selected 
= false;
                                                            
}
                                                            var tani 
= list.Where(item = > item.Value == Model.SearchMokutekitiResults[i].端末ID.ToString()).FirstOrDefault();
                                                            if (tani != null)
                                                            {
                                                                tani.Selected = true;
                                                            }
                                                            }
                            @Html.DropDownListFor(modelItem => modelItem.SearchMokutekitiResults[i].端末ID, list, new { @class = "form-control" }) </ span ></ td >
                     </ tr >
                }

你可能感兴趣的:(小记:MVC4 显示DropDownListFor时绑定失效)