Pass the Selected Values ​​of the ListBox from View to Controller in ASP.NET Core Using jQuery Ajax

This article describes how to pass/send the selected ListBox value to the controller using jQuery Ajax. Let's see it through 4 steps.

Step 1: Controller

The following is a controller code. Microsoft.AspNetCore.Mvc.Rendering is included to use the SelectListItem class. The controller has two action methods, Index() and SampleViewModel(). In the code, a list of movie names is sent to the viewer to bind to the list box.

The SampleViewModel() method retrieves the selected movie ID and text and sends it to the results view.

HomeController.cs
using Microsoft.AspNetCore.Mvc.Rendering;
public class HomeController : Controller
{
   public IActionResult Index()
    {
        List<SelectListItem> MoviesList = new List<SelectListItem>
        {
            new SelectListItem { Value = "1", Text = "Zootopia" },
            new SelectListItem { Value = "2", Text = "Moana" },
            new SelectListItem { Value = "3", Text = "Aladdin"  },
            new SelectListItem { Value = "4", Text = "The Lion King"  },
            new SelectListItem { Value = "5", Text = "Frozen"  }
        };

        SampleViewModel model = new SampleViewModel()
        {
            Movies = MoviesList
        };
        return View(model);
    }

    [HttpPost]
    public IActionResult SampleSubmit(int[] selectedID, string[] selectedText)
    {
        var tuple = new Tuple<int[], string[]>(selectedID, selectedText);
        return View("Result", tuple);
    }
}

Step 2: ListBox View

The following is the view code. To use jQuery, the Google jQuery CDN link is included here. In the selected element here, you can see multiple attribute that makes the selected element a list box, otherwise, it will be a drop-down list.

The size attribute is assigned to 5 so that it displays 5 list items. When you bind over five items, a vertical scroll bar appears.

The Model.Movies property is assigned to the asp-item attribute to bind a list of movie names. The SelectedMovies property is assigned to the asp-for attribute to obtain the selected value.

Index.cshtml
@{
    ViewData["Title"] = "Listbox Tag Helper";
    Layout = null;
}

@model SampleViewModel

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<div>
    <h4>Listbox Tag Helper</h4>

    <select multiple  id="sampleListBox" size="5" asp-items="Model.Movies" asp-for="SelectedMovies"></select>

</div>
<br />
<input id="submitButton" type="button" value="Submit" />

<div id="resultContainer">
</div>

Step 3: jQuery Ajax

The third step is an Ajax jQuery code to pass the selected values to the controller. There are two array values are used here. One is to collect the selected values of the ListBox and the other is to collect the selected text value. Then the array values are sent to /Home/SampleSubmit action. Finally, the result is displayed in the resultContainer div.

<script>
    $("#submitButton").click(function () {

       // Get selected ID
        var selectedIDArray = [];
        $('#sampleListBox :selected').each(function (i, selected) {
            selectedIDArray.push($(selected).val());
        });

        // Get selected text
        var selectedTextArray = [];
        $('#sampleListBox :selected').each(function (i, selected) {
            selectedTextArray.push($(selected).text());
        });

        $.ajax({
            type: 'POST',
            url: '/Home/SampleSubmit',
            traditional: true,
            data: { 'selectedID': selectedIDArray, 'selectedText': selectedTextArray },
            success: function (data) {
                $("#resultContainer").html(data);
            },
            error: function (error) {
                console.log('Error: ' + error);
            }
        });       
    });
</script>

Step 4: Result View

The final view is to display the selected values on the webpage. Where int[] and string[] are passed through the Tuple class. The values are displayed using a loop.

Result.cshtml
@{
    ViewData["Title"] = "Listbox Tag Helper";
    Layout = null;
}

@model Tuple<int[], string[]>

@{
    <h4><u>Selected Results</u></h4>

    if (Model.Item1.Length > 0)
    {
        <div><b>Selected Movies ID</b></div>

        for (int i = 0; i < Model.Item1.Length; i++)
        {
            <div>@Model.Item1[i]</div>
        }
    }

    <br />

    if (Model.Item2.Length > 0)
    {
        <div><b>Selected Movies Text</b></div>

        for (int i = 0; i < Model.Item2.Length; i++)
        {
            <div>@Model.Item2[i]</div>
        }
    }
}

The following is the output of the above code.


I hope the article will helpful for you. Keep Coding


Related Article

Pass the Selected Values ​​of the ListBox to Controller in ASP.NET Core

Comments

Popular posts from this blog

Entity Framework Core (EF) with SQL Server LocalDB

SignalR with JavaScript in ASP.NET Core MVC

Localization in ASP.NET Core MVC with Example