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")
Make sure that you have trim the selected value before you assigning.
//Model
public class SelectType
{
public string Text { get; set; }
public string Value { get; set; }
}
//Controller
var types = new List<SelectType>();
types.Add(new SelectType() { Value = 0, Text = "Select a Type" });
types.Add(new SelectType() { Value = 1, Text = "Family Trust" });
types.Add(new SelectType() { Value = 2, Text = "Unit Trust"});
ViewBag.PartialTypes = types;
//View
@Html.DropDownListFor(m => m.PartialType, new SelectList(ViewBag.PartialTypes, "Value", "Text"), new { id = "Type" })
When you pass an object like this:
new SelectList(Model, "Code", "Name", 0)
you are saying: the Source (Model
) and Key ("Code"
) the Text ("Name"
) and the selected value 0
. You probably do not have a 0
value in your source for Code
property, so the HTML Helper will select the first element to pass the real selectedValue to this control.
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');
});