Arun3x3
Arun3x3

Reputation: 193

Unable to Set DropDownlist with pre-selected value

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" })

Upvotes: 0

Views: 76

Answers (1)

user3559349
user3559349

Reputation:

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.

Upvotes: 1

Related Questions