MVC DropDownList For Selected Value

限于喜欢 提交于 2020-01-16 05:01:26

问题


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


来源:https://stackoverflow.com/questions/31795676/mvc-dropdownlist-for-selected-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!