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.

Answers:

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.

 


Edit this Article
Was this page helpful?
Yes Yes! this solution to the problem was helpful. No No! this solution to the problem was not helpful.. Leave ErnesTech Feedback.Feedback
If you log in, you will be notified when someone leaves a comment.

Other users would like to know if this solution helped you.

jius said:

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

Your Session is Ending
Login to Continue

© 2021 - ErnesTech - Privacy