我无法在MVC中绑定选定的值。有人可以告诉我以下代码有什么问题:
@Html.DropDownListFor(x => Model.Members[i].OccupationCd,
(IEnumerable<SelectListItem>)ViewData["ddl_occupation"],
new { @style = "width:100px", @class = "Occupation required" })
public List<SelectListItem> GetOccupation(string selectedValue)
{
List<SelectListItem> selLstOccupation = new List<SelectListItem>();
selLstOccupation.Add(new SelectListItem { Value = "", Text = "---" + ("Select Occupation") + "---" });
selLstOccupation.AddRange(GetData.AllOccupation());
selLstOccupation = GetData.GetSelectedList(selLstOccupation, selectedValue);
return selLstOccupation;
}
public class Member()
{
//code
//code
public int educationCd { get; set; }
}
我找到了解决方案:
@Html.DropDownListFor(x => Model.Members[i].OccupationCd,new SelectList((IEnumerable<SelectListItem>)ViewData["ddl_occupation"],"Value","Text",Model.Members[i].OccupationCd))
答案 0 :(得分:2)
您必须做两件事才能解决问题。第一个是使用以下实现更改GetOccupation方法
public List<Occupation> GetOccupation()
{
return GetData.AllOccupation();
}
然后您必须将下拉列表初始化更改为以下
@Html.DropDownListFor(x => x.Members[i].OccupationCd,
new SelectList(
(IEnumerable<Occupation>)ViewData["ddl_occupation"],
"OccupationCd",
"@@HERE YOU ADD THE PROPERTY YOU WANT TO VISUALIZE@@",
Model.Members[i].OccupationCd),
"---Select Occupation--",
new { @style = "width:100px", @class = "Occupation required" })
这可以解决您的问题。