Reputation: 645
I am not able to bind the selected value in MVC. Can someone tell me what is wrong with the following code:
@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; }
}
I found the Solution:
@Html.DropDownListFor(x => Model.Members[i].OccupationCd,new SelectList((IEnumerable<SelectListItem>)ViewData["ddl_occupation"],"Value","Text",Model.Members[i].OccupationCd))
Upvotes: 2
Views: 6144
Reputation: 1426
You have to do two things to fix your problem. The first one is to change the GetOccupation method with the following implementation
public List<Occupation> GetOccupation()
{
return GetData.AllOccupation();
}
Then you have to change the dropdown initialization to the following
@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" })
This should fix your problem.
Upvotes: 2