Wednesday, 1 January 2014

Get the values of multiselect Listbox in postback - ASP.NET MVC

In this article we are going to see the how to get the values from the multi select Listbox, To get the values from the multi select we have to pass a IEnumerable of string to the first parameter, and the second parameter must have the IEnumerable of SelectListItem, To pass this both items we have to create a class template and make a strongly typed view.

View
@model EmpApp.Models.SubjectListView

@{
    ViewBag.Title = "List";
}


@using (Html.BeginForm())
{
    @Html.ListBoxFor(x => x.SelectItems, Model.Subjects, new { size = 6 })
    <br />
    <input type="submit" value="Submit" />
}




C#
  [HttpGet]
        public ActionResult List()
        {
            var list = new List<SelectListItem>();
          
            foreach (Subject sub in context.Subjects)
           {
               SelectListItem select = new SelectListItem() {
                   Text=sub.name,
                   Value=sub.id.ToString(),
                   Selected=sub.isselected.Value};
               list.Add(select);
           }

            SubjectListView view = new SubjectListView();
            view.Subjects = list;          
            return View(view);
        }

        [HttpPost]
        public string List(IEnumerable<string> SelectItems)
        {

            if (SelectItems != null)
            {
                return string.Join(",", SelectItems);
            }
            else
            {
                return "No vaues are selected";
            }
        }




Model

    public class SubjectListView
    {

        public IEnumerable<string> SelectItems { set; get; }

        public List<SelectListItem> Subjects { set; get; }
    }



Output

When click on Submit post back output will be 2,3


From this article you can learn how to pass the value from the multi select values from the listbox to the postback.

5 comments:

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. any javascript is needed ?

    ReplyDelete


  3. Given so much information in it. its very useful .perfect explanation about Dot net framework.Thanks for your valuable information. dot net training in chennai | best dot net training in chennai

    ReplyDelete

  4. It is really a great work and the way in which u r sharing the knowledge is excellent.
    Thanks for helping me to understand basic concepts. As a beginner in Dot Net programming your post help me a lot.Thanks for your informative article.
    dot net training in velachery | dot net training institute in velachery

    ReplyDelete