0

Unable to populate dropdonwlist with pre-selected value.Populating with pre-selected value works with viewbag method.However when i am trying the same with a Model based method i find no luck.

public ActionResult Edit(int?id)
{
    Job_ClientVM Vm = new Job_ClientVM();
    Vm.Job_Info = Get_jobdetails(id);
    //4 is desired pre-selected ID value     
    Vm.Recruiters = new SelectList(db.Recruiter_Info.ToList(), "Id", 
    "Recruiter_Name",4);
}

Here is my View

@Html.DropDownListFor(Model => Model.SelectedRecruiterID, Model.Recruiters, "Assign Recruiter", new { @class = "form-control" })
Shahzad
  • 1,315
  • 2
  • 22
  • 42
Arun3x3
  • 193
  • 1
  • 7
  • 17

1 Answers1

1

You need to set the value of SelectedRecruiterID in the GET method before you pass the model to the view.

public ActionResult Edit(int?id)
{
    Job_ClientVM Vm = new Job_ClientVM();
    Vm.Job_Info = Get_jobdetails(id);    
    Vm.Recruiters = new SelectList(db.Recruiter_Info.ToList(), "Id", "Recruiter_Name");
    // Set the value of SelectedRecruiterID
    Vm.SelectedRecruiterID = 4;
    // Pass the model to the view
    return View(Vm);
}

Note that setting the Selected property (the 4th parameter) in the SelectList constructor is pointless - its ignored when binding to a model property (internally the method builds a new IEnumerable<SelectListItem> and sets the Selected property based on the value of the property.

  • Your solution is working but When i am trying to assign Vm.SelectedRecruiterID=Vm.Job_Info.Recruiter_ID; i am facing error cannot convert type int? to int type cast missing. Any idea on how to proceeed – Arun3x3 May 08 '17 at 04:26
  • I do not know what your models are or what types `SelectedRecruiterID` and `Job_Info.Recruiter_ID` are but clearly they are different. Best guess without seeing your models is `Vm.SelectedRecruiterID = Vm.Job_Info.Recruiter_ID.GetValueOrDefault();` –  May 08 '17 at 04:34
  • I fixed the issue by changing SelectedRecruiterID to " public Nullable SelectedRecruiterID { get; set; }" I wanted to ask you if you have any material for good practices on dropdown lists . Thank you – Arun3x3 May 08 '17 at 04:40
  • 1
    Since its a view model it should be nullable anyway (refer [this answer](http://stackoverflow.com/questions/43688968/what-does-it-mean-for-a-property-to-be-required-and-nullable/43689575#43689575) for an explanation). What your doing - creating a view model and including a property for the `SelectList` and using the strongly typed `DropDownListFor()` method is the best practice :). Just remember to repopulate the `Recruiters` property in the POST method if you need to return the view because `ModelState` is invalid. –  May 08 '17 at 04:48