Html.ListBoxFor and Html.ListBoxForFor Example in ASP.NET MVC

In this chapter, you will learn:
  1. What is Html.ListBoxFor Extension Methods?
  2. Html.ListBoxFor Example
  3. How Bind Html.ListBoxFor with a Model
  4. How to display List item in Html.ListBoxFor control
  5. How to send ListBoxFor Value to Controller
  6. Html Attributes of Html.ListBoxFor

What is Html.ListBoxFor Extension Method?

Html.ListBoxFor Extension Method creates ListBox control and allows users to select multiple options in one go. It is very useful when you want to get multiple options for the users. The benefit of using ListBoxFor is, all the options visually appear and a user has the option to select one option as well as more than one options. Here, in this tutorial, I will explain, how to create ListBox in ASP.NET MVC using List Items and then post selected items to controllers.

How to Define Html.ListBoxFor input control?

You can define this control as follows: @Html.ListBoxFor(model => model.property, ItemList, object HtmlAttribute) Model => model.property: It contains the ID of selected items ItemList: It is a list of items Object HtmlAttributes: It sets extra attributes to ListBox Control

Programming Example

Here, I am going to create a TeaList and later I will use this TeaList to show in ListBox and ask the user to select their choice.
Model: UserModel.cs
using System.Collections.Generic;
using System.Web.Mvc;

namespace HtmlHelperDemo.Models
{
    public class UserModel
    {
        public int[] SelectedTeaIds { get; set; }
        public IEnumerable<SelectListItem> TeaList { get; set; }
    }
}
Controller: HomeController.cs
using System.Web.Mvc;
using HtmlHelperDemo.Models;
using System.Collections.Generic;
using System.Linq;

namespace HtmlHelperDemo.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            var model = new UserModel
            {
                SelectedTeaIds = new[] { 2 },
                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;
        }
    }
}
View: Index.cshtml
@using HtmlHelperDemo.Models
@model UserModel
<br /><br />
@using (Html.BeginForm("Index", "Home", 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>
Output: output1

Html Attributes of Html.ListBoxFor

Html Attributes set Html Properties for input control like width, color, value, CSS class etc. Attributes provide additional information about elements and always comes with name="value" pair.
@Html.ListBoxFor(x => x.SelectedTeaIds, Model.TeaList,
    new {
        @style = "width:200px; background-color:yellow; padding:15px;",
        @title = "Select Multiple Options",
        @align = "left",

    })
Html Output

Summary

In this chapter, you learned Html.ListBoxFor() Helper Extension method in ASP.NET MVC 5 with complete programming example. I kept this chapter simple, short and easy so hopefully you will not get any problem in understanding this chapter. In the next chapter, you will learn Html.Hidden() extension method.
 

Share your thought