4

How to Implement Checkbox List in ASP.NET Core

 1 year ago
source link: https://code-maze.com/implement-checkbox-list-aspnetcore/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How to Implement Checkbox List in ASP.NET Core

Publisher Logo

We value your privacy

We and our store and/or access information on a device, such as cookies and process personal data, such as unique identifiers and standard information sent by a device for personalised ads and content, ad and content measurement, and audience insights, as well as to develop and improve products. With your permission we and our partners may use precise geolocation data and identification through device scanning. You may click to consent to our and our partners’ processing as described above. Alternatively you may click to refuse to consent or access more detailed information and change your preferences before consenting. Please note that some processing of your personal data may not require your consent, but you have a right to object to such processing. Your preferences will apply to this website only. You can change your preferences at any time by returning to this site or visit our privacy policy.

How to Implement Checkbox List in ASP.NET Core

Posted by Code Maze | Updated Date Jan 31, 2023 | 0

Code Maze Book Collection

Want to build great APIs? Or become even better at it? Check our Ultimate ASP.NET Core Web API program and learn how to create a full production-ready ASP.NET Core API using only the latest .NET technologies. Bonus materials (Security book, Docker book, and other bonus files) are included in the Premium package!

A Checkbox List is an important feature to encourage multiple selections of inputs in forms.

We will start with a brief overview of the existing checkbox functionality in ASP.NET Core and later on move to the implementation of a checkbox list. 

To download the source code for this article, you can visit our GitHub repository.

Let’s begin.

Overview of Checkbox in ASP.NET Core

To understand how the existing Checkbox functionality works in ASP.NET Core, let’s create a new MVC application using the Visual Studio Project wizard or the dotnet new mvc command.

Let’s create an InitialModel class which contains a boolean IsChecked property:

public class InitialModel
public bool IsChecked { get; set; }
public class InitialModel
{
    public bool IsChecked { get; set; }
}

Now, let’s create a method to return our InitialModel:

public IActionResult Index()
var model = new InitialModel();
return View(model);
public IActionResult Index()
{
    var model = new InitialModel();
    return View(model);
}

Here, we create an Index() action method and instantiate a new InitialModel, which we then pass as a parameter to our View.

Next, we use the existing Index view to create our checkbox:

<form method="post">
<input asp-for="@Model.IsChecked" />
<label>Checkbox</label>
<div>
<button class="btn btn-primary" type="submit">Submit</button>
</div>
</form>
<form method="post">
    <input asp-for="@Model.IsChecked" />
    <label>Checkbox</label>

    <div>
        <button class="btn btn-primary" type="submit">Submit</button>
    </div>
</form>

Here, we create a checkbox, bind it to the IsChecked property of the InitialModel class, and also create a submit button.

To understand the internals of what goes behind the scenes, let’s take a look at the generated markup using the browser dev tools (press Ctrl+Shift+I on Chrome for Windows).

checkbox-internals

The generated markup shows that a hidden field with the name as IsChecked and a value of false is also present. By default, the form renders the hidden field at the end.

Now, when we submit the form, there are 2 possibilities. If we check the input checkbox, both true and false values get submitted. On the other hand, if we do not check the input checkbox, only the false value gets submitted

The ASP.NET Core model binder picks up only the first value on submission, which is true for a checked checkbox and false for an unchecked checkbox.

Now that we understand how a checkbox works in ASP.NET Core, let’s move on to the implementation of a checkbox list. 

Wanna join Code Maze Team, help us produce more awesome .NET/C# content and get paid? >> JOIN US! <<

Populate a Checkbox List

To populate a checkbox list, let’s start by creating a CheckboxViewModel with three properties Id, LabelName and IsChecked:

public class CheckboxViewModel
public int Id { get; set; }
public string LabelName { get; set; }
public bool IsChecked { get; set; }
public class CheckboxViewModel
{
    public int Id { get; set; }
    public string LabelName { get; set; }
    public bool IsChecked { get; set; }
}

Now, we create a static GetCourses() method in a static Repository class to return a few courses:

public static IReadOnlyList<CheckboxViewModel> GetCourses()
return new List<CheckboxViewModel>
new CheckboxViewModel
Id = 1,
LabelName = "Physics",
IsChecked = true
new CheckboxViewModel
Id = 2,
LabelName = "Chemistry",
IsChecked = false
new CheckboxViewModel
Id = 3,
LabelName = "Mathematics",
IsChecked = true
new CheckboxViewModel
Id = 4,
LabelName = "Biology",
IsChecked = false
public static IReadOnlyList<CheckboxViewModel> GetCourses()
{
    return new List<CheckboxViewModel>
    {
        new CheckboxViewModel
        {
            Id = 1,
            LabelName = "Physics",
            IsChecked = true
        },
        new CheckboxViewModel
        {
            Id = 2,
            LabelName = "Chemistry",
            IsChecked = false
        },
        new CheckboxViewModel
        {
            Id = 3,
            LabelName = "Mathematics",
            IsChecked = true
        },
        new CheckboxViewModel
        {
            Id = 4,
            LabelName = "Biology",
            IsChecked = false
        },
    };
}

Then, we implement an HTTP GET action in the HomeController to return the list of courses to the CourseSelection view:

public IActionResult CourseSelection()
var model = Repository.GetCourses();
return View(model);
public IActionResult CourseSelection()
{
    var model = Repository.GetCourses();
    return View(model);
}

Finally, we implement the checkbox list in the CourseSelection view:

<div class="border border-primary">
<form method="post" class="m-5">
<h4>Select Multiple Courses</h4>
<div>
@for (var index = 0; index < @Model.Count(); index++)
<input type="checkbox" asp-for="@Model[index].IsChecked" class="form-check-input" />
<label class="form-check-label" asp-for="@Model[index].IsChecked">
@Model[index].LabelName
</label>
<input type="hidden" asp-for="@Model[index].Id" />
<input type="hidden" asp-for="@Model[index].LabelName" />
<br />
</div>
<div>
<input class="btn btn-primary mt-3" type="submit" value="Submit" />
</div>
</form>
</div>
<div class="border border-primary">
    <form method="post" class="m-5">
        <h4>Select Multiple Courses</h4>
        <div>
            @for (var index = 0; index < @Model.Count(); index++)
            {
                <input type="checkbox" asp-for="@Model[index].IsChecked" class="form-check-input" />
                <label class="form-check-label" asp-for="@Model[index].IsChecked">
                    @Model[index].LabelName
                </label>
                <input type="hidden" asp-for="@Model[index].Id" />
                <input type="hidden" asp-for="@Model[index].LabelName" />
                <br />
            }
        </div>
        <div>
            <input class="btn btn-primary mt-3" type="submit" value="Submit" />
        </div>
    </form>
</div>

We have 3 major key takeaways. First, we use a for loop to bind the input and label elements along with their separate indexes. Next, we leverage the asp-for tag helper with the checkbox element to have the id and name attributes populated correctly. Finally, we create an additional hidden field to post back Id and LabelName properties.

To learn more about tag helpers in ASP.NET Core, check out our great article on Different Ways to Use Select Tag Helper in ASP.NET Core

We run our application and navigate to the /Home/CourseSelection route to view the checkbox list:

multiple-courses-checkbox

Physics and Mathematics are checked by default because we have the boolean property IsChecked = true for them in the GetCourses() method.

Wanna join Code Maze Team, help us produce more awesome .NET/C# content and get paid? >> JOIN US! <<

Get the Selected Checkboxes Values

To retrieve the selected checkbox items in our controller, let’s create a POST action method:

[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult CourseSelection(List<CheckboxViewModel> courses)
var selectedCourses = courses.Where(x => x.IsChecked).ToList();
return RedirectToAction("CourseSelection");
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult CourseSelection(List<CheckboxViewModel> courses)
{
    var selectedCourses = courses.Where(x => x.IsChecked).ToList();
    return RedirectToAction("CourseSelection");
}

First, we use a List<CheckboxViewModel> as a method parameter to grab the form contents. As we use an input type="submit" button in the form we previously created, it will submit the whole form to the POST action method.

Let’s run the app, check/uncheck a few checkboxes and submit the form.

post-action-checkboxlist

We can confirm that the correct model values propagate from the UI to the controller.

Usage of jQuery Ajax to Post the Checkbox List Form

At times, we do not have the luxury of using a submit type button, to post the form to the server side. In such cases, we can leverage jQuery AJAX to perform the form submission.

Let’s use the same Index view to add another form which we will submit via jQuery AJAX:

<div class="border border-secondary mt-3">
<form method="post" class="m-5" id="CoursesForm">
<h4>Select Multiple Courses - jQuery Submit</h4>
<div>
@for (var index = 0; index < @Model.Count(); index++)
<input type="checkbox" asp-for="@Model[index].IsChecked" class="form-check-input" />
<label class="form-check-label" asp-for="@Model[index].IsChecked">
@Model[index].LabelName
</label>
<input type="hidden" asp-for="@Model[index].Id" />
<input type="hidden" asp-for="@Model[index].LabelName" />
<br />
</div>
<div>
<input id="btnSubmit" class="btn btn-info mt-3" type="button" value="Submit" />
</div>
</form>
</div>
<div class="border border-secondary mt-3">
    <form method="post" class="m-5" id="CoursesForm">
        <h4>Select Multiple Courses - jQuery Submit</h4>
        <div>
            @for (var index = 0; index < @Model.Count(); index++)
            {
                <input type="checkbox" asp-for="@Model[index].IsChecked" class="form-check-input" />
                <label class="form-check-label" asp-for="@Model[index].IsChecked">
                    @Model[index].LabelName
                </label>
                <input type="hidden" asp-for="@Model[index].Id" />
                <input type="hidden" asp-for="@Model[index].LabelName" />
                <br />
            }
        </div>
        <div>
            <input id="btnSubmit" class="btn btn-info mt-3" type="button" value="Submit" />
        </div>
    </form>
</div>

Here, we populate the checkbox list using the for loop and use the input type = "button" to submit the form.

Wanna join Code Maze Team, help us produce more awesome .NET/C# content and get paid? >> JOIN US! <<

Next, let’s create a method for the button’s click event in the site.js file:

$(document).ready(function () {
$('#btnSubmit').on('click', function () {
$.ajax({
url: '/Home/CourseSelection',
type: 'POST',
data: $('#CoursesForm').serialize(),
success: function (response) {
console.log('Success');
error: function (xhr) {
console.log(xhr);
$(document).ready(function () {
    $('#btnSubmit').on('click', function () {
        $.ajax({
            url: '/Home/CourseSelection',
            type: 'POST',
            data: $('#CoursesForm').serialize(),
            success: function (response) {
                console.log('Success');
            },
            error: function (xhr) {
                console.log(xhr);
            }
        })
    });
});

Here, we use the POST URL as /Home/CourseSelection and equate the data attribute to the $('#CoursesForm').serialize() method.

The form.serialize() method encodes the form elements in string format, which is then submitted to the server side.

Let’s run the application again, browse to the /Home/CourseSelection view, check all the checkboxes in the second form, and click on Submit button.

courses-form

We see that all the checkbox values pass correctly from the UI to the controller.

post-action-jquery

Conclusion

In this article, we have learned about the internals of a checkbox in ASP.NET Core and the proper way to implement a checkbox list. If you’d like to learn more about ASP.NET Core MVC, check out our great ASP.NET Core MVC Series.

Code Maze Book Collection

Want to build great APIs? Or become even better at it? Check our Ultimate ASP.NET Core Web API program and learn how to create a full production-ready ASP.NET Core API using only the latest .NET technologies. Bonus materials (Security book, Docker book, and other bonus files) are included in the Premium package!

Share:

Subscribe
guest
Label
0 Comments
booklet-200px-width-min.png

Join our 20k+ community of experts and learn about our Top 16 Web API Best Practices.

Leave this field empty if you're human:

© Copyright code-maze.com 2016 - 2023

wpDiscuz


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK