当我给View页面的,性别下拉框设置选中的值后,设置的值一直不起效。
这是我controller:sex的值1为男,2为女
SysUser sysUser = _ISysUserservice.Find<SysUser>(id);
SysUserDTO userDTO = Mapper.Map<SysUser, SysUserDTO>(sysUser);
List<SelectListItem> sexList = new List<SelectListItem>();
if (userDTO.Sex==1)
{
sexList.Add(new SelectListItem { Text = "男", Value = "1", Selected = true });
sexList.Add(new SelectListItem { Text = "女", Value = "2" });
}
else
{
sexList.Add(new SelectListItem { Text = "男", Value = "1" });
sexList.Add(new SelectListItem { Text = "女", Value = "2", Selected = true });
}
ViewData["Sex"] = sexList;
这是我view视图设置下拉框的区域:
@Html.DropDownList("Sex", ViewData["mySex"] as List<SelectListItem>)
根据userDTO实体对象的性别,设置选中的性别,一直不起效。
这里是视图:
通过不断在网上找资料和测试,问题找到了,在controller里面的ViewData["Sex"]的key值“Sex”跟view上的name的值:“Sex”@Html.DropDownList("Sex", ViewData["mySex"] as List<SelectListItem>),会造成Html.DropDownList不识别,所以需要把ViewData里面的key值与view页面,dropdownlist的name值区分开就行。
修改后controller:
SysUser sysUser = _ISysUserservice.Find<SysUser>(id);
SysUserDTO userDTO = Mapper.Map<SysUser, SysUserDTO>(sysUser);
List<SelectListItem> sexList = new List<SelectListItem>();
if (userDTO.Sex==1)
{
sexList.Add(new SelectListItem { Text = "男", Value = "1", Selected = true });
sexList.Add(new SelectListItem { Text = "女", Value = "2" });
}
else
{
sexList.Add(new SelectListItem { Text = "男", Value = "1" });
sexList.Add(new SelectListItem { Text = "女", Value = "2", Selected = true });
}
ViewData["mySex"] = sexList;
view对应@Html.DropDownList这样写:
@Html.DropDownList("Sex", ViewData["mySex"] as List<SelectListItem>)
然后就可以正常选中了: