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
First you should add a new property to your view model class for the dropdown data of type IEnumerable
. 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 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 {
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())
{
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
}