RadioButton Helper in MVC

Introduction

This article shows how to use the RadioButton helper in MVC applications.

Create an ASP.Net Web Application as in Figure 1.

 

Figure 1: Web application 

Choose the MVC template as in Figure 2.

 

Figure 2: MVC template

Add an Employee Controller as in Figure 3.

 

Figure 3: Add Controller

 

Figure 4: EmployeeController

EmployeeController.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace RadioButtonListApp_MVC.Controllers  
  8. {  
  9.     public class EmployeeController : Controller  
  10.     {  
  11.         //  
  12.         // GET: /Employee/  
  13.         public ActionResult Index()  
  14.         {  
  15.             return View();  
  16.         }  
  17.   
  18.         [HttpPost]  
  19.         public string Index(string gender)  
  20.         {  
  21.             string selectedGender = gender;  
  22.             return "Selected Gender is: " + selectedGender;  
  23.         }  
  24.     }  
  25. }  

Add a View as in Figures 5 and 6.

 

Figure 5: Add View

 

Figure 6: Index View

Index.cshtml

  1. @{  
  2.     ViewBag.Title = "Index";  
  3. }  
  4.   
  5. <h2>Index</h2>  
  6.   
  7. @using (Html.BeginForm("Index", "Employee", FormMethod.Post))  
  8. {  
  9.     @Html.RadioButton("gender", "Male")<text>Male</text>  
  10.     @Html.RadioButton("gender", "Female", true)<text>Female</text>  
  11.     <br />  
  12.     <input type="submit" value="Submit" />  
  13. }  
The output of the application is as in Figures 7 and 8.
 

Figure 7: Index

 

Figure 8: Selected value

Summary

In this article we have seen how to use the RadioButton helper in MVC applications.
Happy coding!


Similar Articles
MVC Corporation
MVC Corporation is consulting and IT services based company.