I'm using this Bootstrap Multiselect and my problem is that I cant get the selected values on HttpPost on ASP.Net MVC.
Problems Encountered:
after clicking save, Only the first selected value is the present on the model. (SOLVED)
after clicking save, Only the first selected value is the present on the dropdownlist.
Sample.chtml:
@model SampleProject.Models.SampleViewModel
@using (Html.BeginForm())
{
@Html.DropDownListFor(model => model.Selected, new SelectList(Model.List, "value", "text"), new { @class = "multiselect form-control", multiple = "multiple" })
<input type="submit" value="Save" />
}
Model:
public class SampleViewModel
{
public string[] Selected { get; set; }
public SelectList List { get; set; }
}
Controller:
public class DashboardController : Controller
{
public ActionResult Sample()
{
SampleViewModel model = new SampleViewModel();
model.List = new SelectList(new List<string>() { "1", "2", "3" });
return View(model);
}
[HttpPost]
public ActionResult Sample(SampleViewModel model)
{
model.List = new SelectList(new List<string>() { "1", "2", "3" });
return View(model);
}
}
Selection:
I cant get the selected values correctly on HttpPost
Code Behind/HttpPost: (Wrong)
After HttpPost: (Correct)
Didn't see this answer anywhere, so to solve the issue with having only 1 item selected after the post back you need to use:
A
<select multiple="multiple">
posts back an array of values (not a single value). You propertySelected
needs to beIEnumerable
, for exampleSide note: Since the text and value properties are the same, you can simplify you code by making the
List
propertySelectList
and then in the controller
(although its not clear why you would not use
int
)