質問

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))
役に立ちましたか?

解決

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top