MVC DropDownList For Selected Value

2019-08-04 23:35发布

问题:

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;

}

回答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")