New to Telerik UI for ASP.NET MVC? Download free 30-day trial

Use Strongly-Typed MultiSelect Posted with Form

Environment

Product Progress® Telerik® UI MultiSelect for UI for ASP.NET MVC

Description

How to integrate and use a strongly-typed Telerik UI for ASP.NET MVC MultiSelect within a Telerik UI for ASP.NET MVC Form?

Solution

Using a strongly-typed variable means that the form is bound to a specific model. Rather than a loosely-typed structure like ViewBag. This approach ensures better type safety, validation, and maintainability. Here's how to implement it:

  1. Create ViewModels to store both the available items and the selected values that will be submitted.
  2. Configure and Bind the MultiSelect component to the model.
  3. Implement the Controller Action to populate the model with a list of items. Handle form submissions, binding the user's selections back to the model.
  4. Process the Form Submission by accessing the selected values from the strongly-typed model in the controller.
    @model Telerik.Examples.Mvc.Areas.MultiSelectFormPostStronglyTyped.Models.CountryInfo

    @using (Html.BeginForm())
    {
        <p>Posted values: @(new System.Web.Script.Serialization.JavaScriptSerializer().Serialize(ViewBag.PostedCities ?? new int[] {}))</p>
        @(Html.Kendo().MultiSelectFor(m => m.SelectedCities)
                .DataValueField("ID")
                .DataTextField("Name")
                .BindTo(Model.Cities))
        <br />
        <button>Post</button>
    }
    public class CountryInfo
    {
        public int[] SelectedCities { get; set; }
        public List<City> Cities { get; set; }
    }

    public class City
    {
        public int ID { get; set; }
        public string Name { get; set; }
    }
    public IActionResult Index()
    {
        return View(new CountryInfo
        {
            Cities = GetCities(),
            SelectedCities = new int[] { 1, 3 }
        });
    }

    [HttpPost]
    public ActionResult Index(int[] SelectedCities)
    {
        ViewBag.PostedCities = SelectedCities;
        return View(new CountryInfo
        {
            Cities = GetCities(),
            SelectedCities = SelectedCities
        });
    }

    public List<City> GetCities()
    {
        return new List<City>()
        {
            new City() { ID = 1, Name= "Sao Paulo" },
            new City() { ID = 2, Name= "Toronto" },
            new City() { ID = 3, Name= "New York" },
            new City() { ID = 4, Name= "Vancouver" }
        };
    }

For the complete implementation on how to integrate and use a strongly-typed Telerik UI for ASP.NET MVC MultiSelect within a Telerik UI for ASP.NET MVC Form, refer to this GitHub project.

More ASP.NET MVC MultiSelect Resources

See Also

In this article