×
iFour Logo

A Detailed Explanation on Radio Button Helper and CheckBox Helper in MVC

Drashti varshani - August 19, 2021

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

Sustainable

What is HTML Helper?

MVC provides the HTML Helper class that offers HTML controls in the razor view. HTML helper are methods that return data in the form of string. It binds the model with the view and passes a value from model properties to view and vice versa while submitting the form. There is no server-side control for this, so we have to use the HTML helper class.

RadioButton Helper

What is a RadioButton?

RadioButton is normally connected with the same group name. Users can select only one radio button at a time in the same group. We cannot select multiple radio buttons in the same group.

In MVC there are two ways to create RadioButton using HTML Helper

  • RadioButtonFor
  • RadioButton

RadioButtonFor

HTML.RadioButtonFor is strongly-typed control that is restricted to model property. we need to add a model name on top of the view. Strongly-typed checks for all the errors in code at the compile-time and saves our application not getting errors at run time.


Syntax

@Html.RadioButtonFor()


Example
 @Html.RadioButtonFor(m => m.Gender,"Male")
 @Html.RadioButtonFor(m => m.Gender,"Female")
              

RadioButton

HTML.RadioButton is loosely-typed control that is not restricted to a model property. The HTML.RadioButton is not attached with any model you must pass a string with the same name as the model property to avoid the error at runtime.

Syntax

@Html.RadioButton()


Example
 Male: @Html.RadioButton("Gender","Male")  
 Female: @Html.RadioButton("Gender","Female") 
             

We have to create a project for demonstrating of RadioButton.

Now we need to create a form model. Here I am creating a servey class for a model.

Right-click on the Models folder and add a class for a model.


ServeyFrom.cs
namespace Dynamicappendpartial.Models
{
public class SurveyForm
 {
public int id { 
get; 
set;
 }
[Display(Name = "Name")]
public string U_Name { 
get; 
set;
}
public string Gender { 
get; 
 set;
}
[Display(Name = "ContactNo")]
public long Contact_no { 
get; 
set;
}
}
}
             

Right-click on the controller folder and add the controller for the model class we have created and add the following code inside the controller.


SurveyFormsController
using System;
using System.Collections.Generic;
using System.Data;
using Dynamicappendpartial.Models;
                  
namespace Dynamicappendpartial.Controllers
{
public class SurveyFormsController: Controller
{
private PartialDbContext db = new PartialDbContext();
public ActionResult Create()
{
return View();
}
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "id,U_Name,Gender,Contact_no")] SurveyForm surveyForm)
{
if (ModelState.IsValid)
{
db.SurveyForms.Add(surveyForm);
 db.SaveChanges();
return RedirectToAction("Index");
}
return View(surveyForm);
}  
}
}
                 

Right-click on the method name and add the view to create the method. After adding view run the application.

Auto-Generated-view
[Fig: Auto-Generated view]

In our Form, we require a radio button for gender instead of a text box. we need to modify the view code and add the radio button for Gender.

Create.cshtml

                  
@model Dynamicappendpartial.Models.survey form
                   
@using (Html.BeginForm()) 
{
@Html.AntiForgeryToken()<div class="form-horizontal"><h4>SurveyForm</h4>
<hr />@Html.ValidationSummary(true, &quot;&quot;, new { @class = &quot;text-danger&quot; })<div class="form-group">@Html.LabelFor(model => model.U_Name, htmlAttributes: new { @class = &quot;control-label col-md-2&quot; })<div class="col-md-10">@Html.EditorFor(model => model.U_Name, new { htmlAttributes = new { @class = &quot;form-control&quot; } }) @Html.ValidationMessageFor(model => model.U_Name, &quot;&quot;, new { @class = &quot;text-danger&quot; })</div></div>
<div class="form-group">@Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = &quot;control-label col-md-2&quot; })<div class="col-md-10">@Html.RadioButtonFor(model => model.Gender, &quot;Male&quot;) Male @Html.RadioButtonFor(model => model.Gender, &quot;Female&quot;) Female @Html.ValidationMessageFor(model => model.Gender, &quot;&quot;, new { @class = &quot;text-danger&quot; })</div></div>
<div class="form-group">@Html.LabelFor(model => model.Contact_no, htmlAttributes: new { @class = &quot;control-label col-md-2&quot; })<div class="col-md-10">@Html.EditorFor(model => model.Contact_no, new { htmlAttributes = new { @class = &quot;form-control&quot; } }) @Html.ValidationMessageFor(model => model.Contact_no, &quot;&quot;, new { @class = &quot;text-danger&quot; })</div></div>
<div class="form-group"><div class="col-md-offset-2 col-md-10"><input class="btn btn-default" type="submit" value="Submit" /></div></div></div>
}
<div>@Html.ActionLink(&quot;Back to List&quot;, &quot;Index&quot;)</div>
                

Now run the application and see the view is working as we excepted.


RadioButton
[Fig: RadioButton]

CheckBox Helper

What is a CheckBox?

A checkBox is normally used to select multiple values. A checkbox is similar to a radio button but in a checkbox, we can select multiple values, and is shown as a square box.

In MVC, there are two ways to create CheckBox using HTML Helper

  • CheckBoxFor
  • CheckBox

CheckBoxFor

HTML.CheckBoxFor is strongly-typed control that is restricted to model property. we need to add a model name on top of the view. Strongly-typed checks for all the errors in code at the compile-time and saves our application not getting errors at run time.

Syntax

@Html.CheckBoxFor()

Example

@Html.CheckBoxFor(m => m.ASP.NET MVC)
@Html.CheckBoxFor(m => m.NET Core)
@Html.CheckBoxFor(m => m.JAVA)
@Html.CheckBoxFor(m => m.Angular)
               

CheckBox

HTML.CheckBox is loosely-typed control that is not restricted to a model property. The HTML.CheckBox is not attached with any model you must pass a string with the same name as the model property to avoid the error at runtime. It doesn’t check errors at run time.


Syntax

@Html.CheckBox()


Example
@Html.CheckBox("ASP.NET MVC", true)
@Html.CheckBox("NET Core", false)

@Html.CheckBox("JAVA", false)
@Html.CheckBox("Angular", false)
              

We have to create a project for demonstrating CheckBox.

To Understand checkbox helper, we are using the following table

Databasetable
[Fig: Database table]

Searching for Reliable ASP.Net Development Company ? Your Search ends here.


Our requirement is when we select the checkbox and click on submit button then we get all the checkbox values to append with some string. Show in the below image.


selected-value-output
[Fig: selected value output]

And if we do not select any city and click on submit button we get the following screen.


not-selected-value-output
[Fig: selected value output]

Use the following SQL script to create table User_City and insert data in the table.

CREATE TABLE User_City
(
  ID INT IDENTITY PRIMARY KEY,
  C_Name NVARCHAR(100) NOT NULL,
  IsSelected BIT NOT NULL
)
Insert into User_City values ('Pune', 0)
Insert into User_City values ('Ahmedabad', 0)
Insert into User_City values ('Cuttack', 1)
Insert into User_City values ('Mumbai', 0)
Insert into User_City values ('Bangalore', 0)
Insert into User_City values ('Delhi', 0)
Insert into User_City values ('Hyderabad', 1)
            

Add the ADO.NET data model to retrieve data from the database in our application.

User_City
[Fig: User_City]

Create Controller

Right-click on the controller folder and add the controller for the model class we have created and add the following code inside the controller.

using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Dynamicappendpartial.Models;
            
namespace Dynamicappendpartial.Controllers
{
public class User_CityController : Controller
{
private Entities db = new Entities();
            
[HttpGet]
public ActionResult Index()
{
return View(db.User_City.ToList());
}
[HttpPost]
public string Index(IEnumerable user_Cities)
{
if(user_Cities.Count(x => x.IsSelected) == 0)
{
 return "You have not select any city";
}
else
{
StringBuilder sb = new StringBuilder();
sb.Append("Your selected city is -");
foreach(User_City user_City in user_Cities)
{
if(user_City.IsSelected)
{
sb.Append(user_City.C_Name + " , ");
}
}
sb.Remove(sb.ToString().LastIndexOf(" , "), 1);
return sb.ToString();
}
}
}
}

           

Right-click on the index method and add the index view. Add the following code inside the index view

@model List
@{
ViewBag.Title = "Index";
}
@using (Html.BeginForm())
{
              
              
for (var i = 0; i < Model.Count(); i++)
{
@Html.HiddenFor(it => it[i].ID) @Html.HiddenFor(it => it[i].C_Name) @Html.DisplayFor(it => it[i].C_Name) @Html.CheckBoxFor(it => it[i].IsSelected, new { Style = "vertical-align:3px ; margin-left:2px;}" })
} }

Now run the application and test our requirement it will be working as we excepted.


CheckBox-Example
[Fig: CheckBox Example]

Conclusion

Here in this blog, we learned the usage of RadioButton and CheckBox using HTML Helper in MVC application. We have also gone through various types with real-time example.

A Detailed Explanation on Radio Button Helper and CheckBox Helper in MVC Table of Content 1. What is HTML Helper? 2. RadioButton Helper 2.1. What is a RadioButton? 2.2. RadioButtonFor 2.3. RadioButton 3. CheckBox Helper 3.1. What is a CheckBox? 3.2. CheckBoxFor 3.3. CheckBox 4. Conclusion What is HTML Helper? MVC provides the HTML Helper class that offers HTML controls in the razor view. HTML helper are methods that return data in the form of string. It binds the model with the view and passes a value from model properties to view and vice versa while submitting the form. There is no server-side control for this, so we have to use the HTML helper class. RadioButton Helper What is a RadioButton? RadioButton is normally connected with the same group name. Users can select only one radio button at a time in the same group. We cannot select multiple radio buttons in the same group. In MVC there are two ways to create RadioButton using HTML Helper RadioButtonFor RadioButton RadioButtonFor HTML.RadioButtonFor is strongly-typed control that is restricted to model property. we need to add a model name on top of the view. Strongly-typed checks for all the errors in code at the compile-time and saves our application not getting errors at run time. Syntax @Html.RadioButtonFor() Example @Html.RadioButtonFor(m => m.Gender,"Male") @Html.RadioButtonFor(m => m.Gender,"Female") RadioButton HTML.RadioButton is loosely-typed control that is not restricted to a model property. The HTML.RadioButton is not attached with any model you must pass a string with the same name as the model property to avoid the error at runtime. Syntax @Html.RadioButton() Example Male: @Html.RadioButton("Gender","Male") Female: @Html.RadioButton("Gender","Female") We have to create a project for demonstrating of RadioButton. Now we need to create a form model. Here I am creating a servey class for a model. Right-click on the Models folder and add a class for a model. ServeyFrom.cs namespace Dynamicappendpartial.Models { public class SurveyForm { public int id { get; set; } [Display(Name = "Name")] public string U_Name { get; set; } public string Gender { get; set; } [Display(Name = "ContactNo")] public long Contact_no { get; set; } } } Right-click on the controller folder and add the controller for the model class we have created and add the following code inside the controller. Read More: How To Upload And Return Files In Asp.net Mvc? SurveyFormsController using System; using System.Collections.Generic; using System.Data; using Dynamicappendpartial.Models; namespace Dynamicappendpartial.Controllers { public class SurveyFormsController: Controller { private PartialDbContext db = new PartialDbContext(); public ActionResult Create() { return View(); } [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create([Bind(Include = "id,U_Name,Gender,Contact_no")] SurveyForm surveyForm) { if (ModelState.IsValid) { db.SurveyForms.Add(surveyForm); db.SaveChanges(); return RedirectToAction("Index"); } return View(surveyForm); } } } Right-click on the method name and add the view to create the method. After adding view run the application. [Fig: Auto-Generated view] In our Form, we require a radio button for gender instead of a text box. we need to modify the view code and add the radio button for Gender. Create.cshtml @model Dynamicappendpartial.Models.survey form @using (Html.BeginForm()) { @Html.AntiForgeryToken()SurveyForm @Html.ValidationSummary(true, "", new { @class = "text-danger" })@Html.LabelFor(model => model.U_Name, htmlAttributes: new { @class = "control-label col-md-2" })@Html.EditorFor(model => model.U_Name, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.U_Name, "", new { @class = "text-danger" }) @Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label col-md-2" })@Html.RadioButtonFor(model => model.Gender, "Male") Male @Html.RadioButtonFor(model => model.Gender, "Female") Female @Html.ValidationMessageFor(model => model.Gender, "", new { @class = "text-danger" }) @Html.LabelFor(model => model.Contact_no, htmlAttributes: new { @class = "control-label col-md-2" })@Html.EditorFor(model => model.Contact_no, new { htmlAttributes = new { @class = "form-control" } }) @Html.ValidationMessageFor(model => model.Contact_no, "", new { @class = "text-danger" }) } @Html.ActionLink("Back to List", "Index") Now run the application and see the view is working as we excepted. [Fig: RadioButton] CheckBox Helper What is a CheckBox? A checkBox is normally used to select multiple values. A checkbox is similar to a radio button but in a checkbox, we can select multiple values, and is shown as a square box. In MVC, there are two ways to create CheckBox using HTML Helper CheckBoxFor CheckBox CheckBoxFor HTML.CheckBoxFor is strongly-typed control that is restricted to model property. we need to add a model name on top of the view. Strongly-typed checks for all the errors in code at the compile-time and saves our application not getting errors at run time. Syntax @Html.CheckBoxFor() Example @Html.CheckBoxFor(m => m.ASP.NET MVC) @Html.CheckBoxFor(m => m.NET Core) @Html.CheckBoxFor(m => m.JAVA) @Html.CheckBoxFor(m => m.Angular) CheckBox HTML.CheckBox is loosely-typed control that is not restricted to a model property. The HTML.CheckBox is not attached with any model you must pass a string with the same name as the model property to avoid the error at runtime. It doesn’t check errors at run time. Syntax @Html.CheckBox() Example @Html.CheckBox("ASP.NET MVC", true) @Html.CheckBox("NET Core", false) @Html.CheckBox("JAVA", false) @Html.CheckBox("Angular", false) We have to create a project for demonstrating CheckBox. To Understand checkbox helper, we are using the following table [Fig: Database table] Searching for Reliable ASP.Net Development Company ? Your Search ends here. See here Our requirement is when we select the checkbox and click on submit button then we get all the checkbox values to append with some string. Show in the below image. [Fig: selected value output] And if we do not select any city and click on submit button we get the following screen. [Fig: selected value output] Use the following SQL script to create table User_City and insert data in the table. CREATE TABLE User_City ( ID INT IDENTITY PRIMARY KEY, C_Name NVARCHAR(100) NOT NULL, IsSelected BIT NOT NULL ) Insert into User_City values ('Pune', 0) Insert into User_City values ('Ahmedabad', 0) Insert into User_City values ('Cuttack', 1) Insert into User_City values ('Mumbai', 0) Insert into User_City values ('Bangalore', 0) Insert into User_City values ('Delhi', 0) Insert into User_City values ('Hyderabad', 1) Add the ADO.NET data model to retrieve data from the database in our application. [Fig: User_City] Create Controller Right-click on the controller folder and add the controller for the model class we have created and add the following code inside the controller. using System.Collections.Generic; using System.Linq; using System.Text; using System.Web.Mvc; using Dynamicappendpartial.Models; namespace Dynamicappendpartial.Controllers { public class User_CityController : Controller { private Entities db = new Entities(); [HttpGet] public ActionResult Index() { return View(db.User_City.ToList()); } [HttpPost] public string Index(IEnumerable user_Cities) { if(user_Cities.Count(x => x.IsSelected) == 0) { return "You have not select any city"; } else { StringBuilder sb = new StringBuilder(); sb.Append("Your selected city is -"); foreach(User_City user_City in user_Cities) { if(user_City.IsSelected) { sb.Append(user_City.C_Name + " , "); } } sb.Remove(sb.ToString().LastIndexOf(" , "), 1); return sb.ToString(); } } } } Right-click on the index method and add the index view. Add the following code inside the index view @model List @{ ViewBag.Title = "Index"; } @using (Html.BeginForm()) { for (var i = 0; i < Model.Count(); i++) { @Html.HiddenFor(it => it[i].ID) @Html.HiddenFor(it => it[i].C_Name) @Html.DisplayFor(it => it[i].C_Name) @Html.CheckBoxFor(it => it[i].IsSelected, new { Style = "vertical-align:3px ; margin-left:2px;}" }) } } Now run the application and test our requirement it will be working as we excepted. [Fig: CheckBox Example] Conclusion Here in this blog, we learned the usage of RadioButton and CheckBox using HTML Helper in MVC application. We have also gone through various types with real-time example.

Author Bio

User Image

Author Name : Drashti varshani

Drasti varshani is an Asp.Net MVC fanatic. Her extensive knowledge in the subject and passion for helping others makes her exceptionally unique. She provides undeniable insights on Microsoft technologies for various platforms.

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 

Blog Our insights

Features to look for in the Transportation and Logistics software
Features to look for in the Transportation and Logistics software

Table of Content 1. Real-time tracking with security-access limitations 2. Order management dashboard 3. Load planning 4. Order, inventory, and warehouse management 5....

Read More
Benefits of adopting logistics software for transportation business
Benefits of adopting logistics software for transportation business

Table of Content 1.Imperative when it comes to supply chains 2.Allow companies to automate processes 3.Track the Vehicle in Real-Time 4.Helps to keep track of all the...

Read More
6 Benefits of the Transportation Management System
6 Benefits of the Transportation Management System

Nothing has benefited the supply chain operations as Transportation Management Software has. Transport Management System or TMS automates the basic transportation processes and provides...

Read More