A day with .Net

My day to day experince in .net

Passing all the values (including unselected) of a list box to MVC controller.

Posted by vivekcek on February 26, 2014

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>
Advertisements

One Response to “Passing all the values (including unselected) of a list box to MVC controller.”

  1. I think that the second param of .prop line must be true, not “selected”.
    I did the correction on my code and works fine!

    Thank you, Sir!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s