I am trying to populate the selected value field of an MVC drop down list, but I have been unsuccessful. I am using MVC 5.1.
Here is a screenshot of the selected value and the model showing sales receipts:
Instead of sales receipts being selected, the model defaults to estimates:
When I use ViewData, the drop down works successfully:
Html.DropDownList("JMASettings.InvoiceMode")
Here is my code:
public void GetInvoiceMode(JMASettings model)
{
Dictionary<string, string> modes = new Dictionary<string, string>();
modes.Add("Estimates", "Estimates");
modes.Add("Invoices Only (Payments If Paid)", "Invoices");
modes.Add("Invoices No Payments", "InvoicesNoPayments");
modes.Add("Sales Receipts", "Sales Receipts");
if (Session["dataSource"] != null && Session["dataSource"].ToString() == "QBD")
modes.Add("Sales Orders", "Sales Orders");
IList<SelectListItem> ilSelectList = new List<SelectListItem>();
foreach (KeyValuePair<string, string> mode in modes)
{
SelectListItem selectListItem = new SelectListItem();
selectListItem.Text = mode.Key;
selectListItem.Value = mode.Value;
if (model.InvoiceMode == mode.Value)
selectListItem.Selected = true;
else if (String.IsNullOrEmpty(model.InvoiceMode) && mode.Key == "Sales Receipts")
selectListItem.Selected = true;
ilSelectList.Add(selectListItem);
}
ViewData["JMASettings.InvoiceMode"] = ilSelectList;
}
Keep the property which represents the selected item on your view model like this.
Now when you have to render the view, load the Modes collection and set the SelectedMode to whatever you want
In your view,