How to MVC 5 drop down (multiple select) box

后端 未结 2 528
感情败类
感情败类 2021-01-24 03:22

I\'m having trouble with this drop down box, just cant seem to get it right, here\'s the code:

View (Index.cshtml):

@using EvaSimulator.Models
@Model Eva         


        
相关标签:
2条回答
  • 2021-01-24 03:43

    Use the For helper instead to get compile time checking. When using MultiSelectList we need to bind the selected values to an array in the first param, then you can pass your select list with the values to be shown in the second param.

     public string[] SelectedValues { get; set; }
    
     public MultiSelectList DropDownList { get; set; }
    

    Controller:

     mv.DropDownList = new MultiSelectList(/*Your list of items here*/)
    

    View:

     @Html.DropDownListFor(x => Model.SelectedValues, Model.DropDownList)
    
    0 讨论(0)
  • 2021-01-24 04:02

    First you should add a new property to your view model class for the dropdown data of type IEnumerable<SelectListItem>. We will add a second property of array type(since you want a multi select) to hold the selected option values .

    public class ModelVariables
    {
      public IEnumerable<SelectListItem> Options {set;get;}
      public string[] SelectedOptions { set;get;}
    }
    

    Now in your GET action, create an object of this view model,populate the Options property and send to the view.

    public ActionResult Create()
    {
      var vm = new ModelVariables();
      vm.Options = new List<SelectListItem> {
         new SelectListItem { Value="MI", Text="Michigan" },
         new SelectListItem { Value="NY", Text="New York" },
      };
      return View(vm);
    }
    

    Now in your view ,use the Html.ListBoxFor helper method

    @model ModelVariables
    @using(Html.BeginForm())
    { 
       <label> Select items <label>
       @Html.ListBoxFor(s=>s.SelectedOptions,Model.Options)
       <input type="submit" />
    }
    

    Now in your HttpPost action, you can have the same view model as your method parameter and Model binder will be able to map the posted form data to an object of that. The selected options from the UI will be available in the SelectedOptions property of the view model object.

    [HttpPost]
    public ActionResult Create(ModelVariables model)
    {
      // check model.SelectedOptions property value
     // to do : Return something
    }
    
    0 讨论(0)
提交回复
热议问题