Reputation: 199
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)
Upvotes: 9
Views: 17469
Reputation: 81
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:
@Html.ListBoxFor(..
instead of @Html.DropDownListFor
Upvotes: 5
Reputation:
A <select multiple="multiple">
posts back an array of values (not a single value). You property Selected
needs to be IEnumerable
, for example
public string[] Selected { get; set; }
Side note: Since the text and value properties are the same, you can simplify you code by making the List
property SelectList
public SelectList List { get; set; }
and then in the controller
model.List = new SelectList(new List<string>() { "1", "2", "3" })
(although its not clear why you would not use int
)
Upvotes: 12