1

Working with Asp.net C#, MVC3 Razor View, I am trying to set dropdown list value while editing a record and have following Model:

public class EditEmployeeModel
    {
        ....
        public int? DepartmentId { get; set; }

        [Required(ErrorMessage = "Department is must")]
        [Display(Name = "Department")]
        public string Department { get; set; }

        public List<SelectListItem> Departments { get; set; }

        .....
}

Controller:

 public ActionResult Edit(string id)
    {
        EditEmployeeModel model = respo.GetEmployeeByID(id);
        model.Departments = GetDepartments();
        return View(model);
    }

And View:

<div class="editor-field">
@Html.DropDownListFor(m => m.DepartmentId, Model.Departments, new { id ="ddlstDepartments"})
@Html.ValidationMessageFor(m => m.Department)
</div>

But when view is loaded for editing, dropdownlist always shows the default/first item selected. Could someone please help here.

Rakesh Singh
  • 143
  • 2
  • 11
  • Try like this `Html.DropDownListFor(m => m.DepartmentId, Model.Departments,"--Select Department")` – Karthik Chintala Mar 06 '13 at 06:15
  • Make sure you check all the answers and check the one that is correct for you situation. Also vote up/down if you consider it helpful so that other users in your situation should be helped if they come across your question. – radu florescu Mar 06 '13 at 06:38

2 Answers2

1

Have you tried setting selected = true for one element in the list before passing it to view?

There are several questions on So that might help you like this one:

Community
  • 1
  • 1
radu florescu
  • 4,315
  • 10
  • 60
  • 92
-1

make sure the DepartmentId in model

   EditEmployeeModel model = respo.GetEmployeeByID(id);
   //model.DepartmentId

is not null, and if you want to show a --Select Department-- label as @Karthik suggested try

Html.DropDownListFor(m => m.DepartmentId, Model.Departments,"--Select Department")
Dakait
  • 2,531
  • 1
  • 25
  • 43
  • I think your answer has nothing to do with the question. He receives the data in the dropdown and he could not select certain element as selected from controller side. – radu florescu Mar 06 '13 at 06:36
  • 2
    @Floradu88 its the **edit** ActionResult and the value of DepartmentID is supposed to be selected while adding the Employee ... and yes i know OP is getting the data in List but what option of List was previously selected by the used has to be persisted in database and set via the controller... if the OP cannot set the selected element from controller side then how you are supposed to display the previously selected department ??? – Dakait Mar 06 '13 at 07:05
  • DepartmentId is not coming as NULL, it has a value (12 in my case) but still, dropdownlist is not set to the item having value 12 – Rakesh Singh Mar 07 '13 at 05:05