1

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:

enter image description here

Instead of sales receipts being selected, the model defaults to estimates:

enter image description here

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;

}

1 Answer 1

1

Keep the property which represents the selected item on your view model like this.

public class CreateOrderVM
{
  public List<SelectListItem> Modes {set;get;}
  public string SelectedMode {set;get;}

  public CreateOrderVM()
  {
    this.Modes=new List<SelectListItem>();
  }
}

Now when you have to render the view, load the Modes collection and set the SelectedMode to whatever you want

public ActionResult Show()
{
  var vm=new CreateOrderVM();
  vm.Modes = GetModes();

  //Set one of them as selected
  vm.SelectedMode="B";

  return View(vm);
}
private List<SelectListItem> GetModes()
{
  var list=new List<SelectListItem>();
  //hard coded for demo.Replace with actual values

  list.Add(new SelectListItem { Value="A", Text="A"});
  list.Add(new SelectListItem { Value="B", Text="B"});
  list.Add(new SelectListItem { Value="C", Text="C"});
  return list;
}

In your view,

@model YourNamespace.CreateOrderVM

@Html.DropdownListFor(s=>s.SelectedMode,Model.Modes,"Select")
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.