×

iFour Logo

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

Kapil Panchal - August 19, 2021

Listening is fun too.

Straighten your back and cherish with coffee - PLAY !

  • play
  • pause
  • pause
A Detailed Explanation on Radio Button Helper and CheckBox Helper in MVC

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()

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.

 

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 ?

 

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 ? CONTACT US   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.
Kapil Panchal

Kapil Panchal

A passionate Technical writer and an SEO freak working as a Content Development Manager at iFour Technolab, USA. With extensive experience in IT, Services, and Product sectors, I relish writing about technology and love sharing exceptional insights on various platforms. I believe in constant learning and am passionate about being better every day.

Build Your Agile Team

Enter your e-mail address Please enter valid e-mail

Categories

Ensure your sustainable growth with our team

Talk to our experts
Sustainable
Sustainable
 
Blog Our insights
How Spatial Data Analysis Improves Healthcare
How Spatial Data Analysis Improves Healthcare

Do you know when geospatial analysis took traction in healthcare? It was when John Snow, a London-based physician, used it to analyze the spread of cholera, which ultimately proved...

4 Types of Power BI Dashboards: Analytical, Strategic, Operational, and Tactical
4 Types of Power BI Dashboards: Analytical, Strategic, Operational, and Tactical

One interesting aspect you truly love about Power BI, as a CTO, is how it lets you step back and see the bigger picture of your business. Isn’t it? Without getting bogged down in minute...

Power Apps Integration Challenges: Expert Insights & Solutions
Power Apps Integration Challenges: Expert Insights & Solutions

Power Apps Integration Challenges: Insights from 11 Experts Microsoft Power Apps has caught great hype in recent days. Why? because it helps you build apps 50% faster, saves 250+...