How to Bind a CheckBox data to a Model Integer Property in DotNet Core 2.2

When working in ASP.Net Core 2.2 Razor Engine, you might find yourself wanting to bind data from a checkbox Form in the View to the Model Object attribute that is an integer in the Controller.

Login to See the Rest of the Answer


1. Go to the Model class and add a property of the type you want to present in the Form. In this case, it will be a boolean since we want to present a Checkbox to the user and then handle the True or False to represent an integer 1 or 0.

2. After the boolean property has been added to the Model, make sure you include a "using System.ComponentModel.DataAnnotations.Schema; namespace in order to progress to the next step.

3. After the API namespace has been in included in your Model, then prefix the property in this case: 

     [NotMapped] //Not mapped tells the Database Context that the column is not required
     public bool YourPropertyName get; set;

4. In the View or Front-End, you can bind the checkbox with the boolean property like so: 

      Html.CheckBoxFor(x = x.YourPropertyname)

5. In the Controller, you can then handle the boolean coming in as a Model data that has been posted into an integer.



jius said:

Do you know how to use javascript:void(0) in Dotnet core 2.2? Thank you, in advance.

Posted On: September 26, 2019 16:13:06 PM

© 2024 - ErnesTech - Privacy
E-Commerce Return Policy