A day with .Net

My day to day experince in .net

MVC Sending Listbox selected values to controller – Code Snippet

Posted by vivekcek on February 25, 2014

1. Define model

 public class MyViewModel
    {
        public string[] SelectedValues { get; set; }
        public List<SelectListItem> Items { get; set; }
    }

2. Define controller

public class HomeController : 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(string[] Values)
        {
            return Json(new { message = string.Format("Number of values {0}", Values.Length) }, JsonRequestBehavior.AllowGet);
        }
    }

3. Define View

@model MvcListBox.Models.MyViewModel

@{
    ViewBag.Title = "Home Page";
}

@Html.ListBoxFor(m => m.SelectedValues, Model.Items, new { id = "myList" })
@Html.ActionLink("My Action", "GetResult", null, new { id = "myLink" })

@Scripts.Render("~/bundles/jquery")

<script type="text/javascript">
    $(document).ready(function () {

        $("#myLink").click(function () {

            var selectedValues = $('#myList').val();
            $.getJSON(this.href, $.param({ values: selectedValues }, true), function (result) {
                alert(result.message);
            });
            return false;
        });

    });
</script>
Advertisements

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