Html.DropdownListFor selected value not being set
Your code has some conceptual issues:
First,
@Html.DropDownListFor(n => n.OrderTemplates, new SelectList(Model.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1), "Please select an order template")
When using DropDownListFor, the first parameter is the property where your selected value is stored once you submit the form. So, in your case, you should have a SelectedOrderId
as part of your model or something like that, in order to use it in this way:
@Html.DropDownListFor(n => n.SelectedOrderId, new SelectList(Model.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1), "Please select an order template")
Second,
Aside from using ViewBag, that is not wrong but there are better ways (put that information in the ViewModel instead), there is a "little bug" (or an unspected behavior) when your ViewBag property, where you are holding the SelectList, is the same name of the property where you put the selected value. To avoid this, just use another name when naming the property holding the list of items.
Some code I would use if I were you to avoid this issues and write better MVC code:
Viewmodel:
public class MyViewModel{
public int SelectedOrderId {get; set;}
public SelectList OrderTemplates {get; set;}
// Other properties you need in your view
}
Controller:
public ActionResult MyAction(){
var model = new MyViewModel();
model.OrderTemplates = new SelectList(db.OrderTemplates, "OrderTemplateId", "OrderTemplateName", 1);
//Other initialization code
return View(model);
}
In your View:
@Html.DropDownListFor(n => n.SelectedOrderId, Model.OrderTemplates, "Please select an order template")
For me was not working so worked this way:
Controller:
int selectedId = 1;
ViewBag.ItemsSelect = new SelectList(db.Items, "ItemId", "ItemName",selectedId);
View:
@Html.DropDownListFor(m => m.ItemId,(SelectList)ViewBag.ItemsSelect)
JQuery:
$("document").ready(function () {
$('#ItemId').val('@Model.ItemId');
});