In normal case when we submit form only the selected values of the listbox is bind to model.
If you want to get all the values of the listbox on post. Try the blow tip.
Add the below jquery function, which select all the list box items before submit.
<script type="text/javascript"> $(document).ready(function () { $("#myForm").submit(function (e) { $("#myList option").prop("selected", "selected"); }); }); </script>
Complete solution is given below.
1. Define the model.
public class MyViewModel { public string[] SelectedValues { get; set; } public List<SelectListItem> Items { get; set; } }
2. Define the controller
public ActionResult Index() { MyViewModel m = new MyViewModel() { Items = new List<SelectListItem>() { new SelectListItem { Value = "1", Text = "item 1" }, new SelectListItem { Value = "2", Text = "item 2" }, new SelectListItem { Value = "3", Text = "item 3" }, new SelectListItem { Value = "4", Text = "item 4" }, } }; return View(m); } public ActionResult GetResult(MyViewModel model) { return RedirectToAction("Index"); }
3. Define the view
@model MvcListBox.Models.MyViewModel @{ ViewBag.Title = "Home Page"; } @using (Html.BeginForm("GetResult", "Home", FormMethod.Post, new { id = "myForm" })) { @Html.ListBoxFor(m => m.SelectedValues, Model.Items, new { id = "myList" }) <button type="submit">Submit</button> } @Scripts.Render("~/bundles/jquery") <script type="text/javascript"> $(document).ready(function () { $("#myForm").submit(function (e) { $("#myList option").prop("selected", "selected"); }); }); </script>