How to select multiple items from ListBoxFor and pass to controller Post method

1.2k views Asked by At

How am I able to select multiple items in a Listbox that will be passed to the controller's Post model parameter? I'm able to physically select multiple via holding CTRL, but when I submit, I get the validation error message, "The field TagId must be a number." It only submits with one item selected.

Create View Form showing multiple items selected

The List Box

@Html.ListBoxFor(model => model.allTags[0].TagId, new SelectList(Model.allTags, "TagId", "Name"), new { @class = "form-control", @Id = "SelectTags", @style = "width:200px;height:300px;" })

The controller Post method

        [HttpPost]
        public ActionResult Create(CreateRecipe model) 
        {
            try
            {
                // TODO: Add insert logic here

                return RedirectToAction("ViewRecipes");
            }
            catch
            {
                return View();
            }
        }

Thank you

1

There are 1 answers

1
Jack J Jun On BEST ANSWER

You can try the following code to select multiple items from ListBoxFor and pass it to controller Post method.

Controller:

 public class TestController : Controller
    {
        // GET: Test
        public ActionResult Index()
        {
            var model = new UserModel
            {
                SelectedTeaIds = new[] { 3 },
                TeaList = GetAllTeaTypes()
            };
            return View(model);
        }

        [HttpPost]
        public ActionResult Index(UserModel model)
        {
            model.TeaList = GetAllTeaTypes();
            if (model.SelectedTeaIds != null)
            {
                List<SelectListItem> selectedItems = model.TeaList.Where(p => model.SelectedTeaIds.Contains(int.Parse(p.Value))).ToList();
                foreach (var Tea in selectedItems)
                {
                    Tea.Selected = true;
                    ViewBag.Message += Tea.Text + " | ";
                }
            }
            return View(model);
        }

        public List<SelectListItem> GetAllTeaTypes()
        {
            List<SelectListItem> items = new List<SelectListItem>();
            items.Add(new SelectListItem { Text = "General Tea", Value = "1" });
            items.Add(new SelectListItem { Text = "Coffee", Value = "2" });
            items.Add(new SelectListItem { Text = "Green Tea", Value = "3" });
            items.Add(new SelectListItem { Text = "Black Tea", Value = "4" });
            return items;
        }
    }

Model:

public class UserModel
    {
        public int[] SelectedTeaIds { get; set; }
        public IEnumerable<SelectListItem> TeaList { get; set; }
    }

Index.cshtml:

@using WebApplication1.Models
@using System
@model UserModel
@{
    ViewBag.Title = "Index";
}


<b>Select Tea Type: </b>
<br />

@using (Html.BeginForm("Index", "Test", FormMethod.Post))
{
    <b>Select Tea Type: </b>
    <br />
    @Html.ListBoxFor(x => x.SelectedTeaIds, Model.TeaList, new { style = "width:200px" })
    <br />
    <input type="submit" value="submit" />
}

<h4>You Selected</h4>
<b style="color:red">Tea Type: @ViewBag.Message</b>

Result:

enter image description here