0

I have this code below working fine.

Sample output

Computer Department

Technical Department

Product Department

Let say my department is Product Department. I am the the who log-in in the system / project. It is possible to first load my department in the DropDownList?. What I mean in first load is upon loading of the dropdown my department is set to be the first.

Controller

ViewBag.DepartmentId = new SelectList(db.Departments, "DepartmentId", "DepartmentDesc", null).OrderBy(m => m.Text);

HTML

@Html.DropDownList("DepartmentId ", ViewData["DepartmentId "] as SelectList, "", new { @style = "width:130px;" })
Community
  • 1
  • 1
KiRa
  • 924
  • 3
  • 17
  • 42
  • Just set the value of property`DepartmentId` in the GET method before you pass the model in the view, and that option will be selected –  Jan 20 '17 at 07:57
  • @StephenMuecke How do I set the property value?. – KiRa Jan 20 '17 at 07:59
  • Refer [this answer](http://stackoverflow.com/questions/41719293/mvc5-how-to-set-selectedvalue-in-dropdownlistfor-html-helper/41731685#41731685) –  Jan 20 '17 at 08:01
  • Note also that you cannot use the same name for the property your binding to and the SelectList (refer [this answer](http://stackoverflow.com/questions/37161202/will-there-be-any-conflict-if-i-specify-the-viewbag-name-to-be-equal-to-the-mode/37162557#37162557)) - rename the `ViewData` property to say `DepartmentList` –  Jan 20 '17 at 08:03
  • @StephenMuecke Just want to ask. How did you get the `Model.TipoviDepozita`?. Refer to your first link. and what is `"NotAModelProperty", `? – KiRa Jan 20 '17 at 08:06
  • Not sure what you mean (thats is OP's data) - but you need `ViewBag.DepartmentList = new SelectList(db.Departments.Orderby(x => x.DepartmentDesc), "DepartmentId", "DepartmentDesc");` - or better use a view model –  Jan 20 '17 at 08:10
  • @StephenMuecke Can you provide an example of view model?. – KiRa Jan 20 '17 at 08:15
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/133617/discussion-between-stephen-muecke-and-kira). –  Jan 20 '17 at 08:16

2 Answers2

0

Where you set null in new SelectList, set your selected option.

ViewBag.DepartmentId = new SelectList(db.Departments.OrderBy(m => m.Text), "DepartmentId", "DepartmentDesc", selectedDepartmentId);
Federico Alecci
  • 914
  • 6
  • 14
0

Try this code:-

ViewBag.DepartmentId = new SelectList(db.Departments, "DepartmentId", "DepartmentDesc",SelectedDepartmentId).OrderBy(m => m.Text);

And

@Html.DropDownList("DepartmentId ", ViewData["DepartmentId "] as SelectList, "My Department", new { @style = "width:130px;" })
manika
  • 187
  • 2
  • 13