.Net MVC Html.CheckBox tutorial with examples

HTML.CheckBox is a method provided by the HtmlHelper class in .NET MVC that generates an HTML checkbox input element. In this blog, we will explore how to use Html.CheckBox in .NET MVC and the various options available.

Creating a Checkbox using HTML.CheckBox

HTML.CheckBox is a simple method that generates an HTML checkbox input element. Here is an example of how to use it:
@Html.CheckBox("rememberMe", false, new { @class = "checkbox" })
In the above example, we are using the CheckBox method to create a checkbox input element with the name "rememberMe". The second parameter is the initial value of the checkbox, which is false in this case. The third parameter is an anonymous object that contains HTML attributes for the checkbox, such as the CSS class "checkbox".

When we run this code, it will generate the following HTML:


The first input element is the checkbox itself. The second input element is a hidden field that ensures that the checkbox value is always submitted with the form, even if the checkbox is not checked.

By default, the value of the checkbox is "true" when it is checked and "false" when it is not checked. However, we can specify different values for the checked and unchecked states by passing them as the third and fourth parameters to Html.CheckBox.

Html.CheckBox Example

    @Html.CheckBox("CheckBox_Id") Accept Policy
    

Generated HTML Tag

    
     Accept Policy
    

 


Html.CheckBox set by default Checked

    @Html.CheckBox("CheckBox_Id", true) Accept Policy
    

Generated HTML Tag

    
     Accept Policy
    

 


Disable Html.CheckBox

    @Html.CheckBox("CheckBox_Id", new { @disabled = "disabled" }) Accept Policy
    

Generated HTML Tag

    
     Accept Policy
    
 
Asp.Net Ajax Control Toolkit tutorials.

Give your valuable comments.

Name
Email
Comment
8 + 3 =
 

About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice