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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
-
- namespace RadioButtonListApp_MVC.Controllers
- {
- public class EmployeeController : Controller
- {
-
-
- public ActionResult Index()
- {
- return View();
- }
-
- [HttpPost]
- public string Index(string gender)
- {
- string selectedGender = gender;
- return "Selected Gender is: " + selectedGender;
- }
- }
- }
Add a View as in Figures 5 and 6.
Figure 5: Add View
Figure 6: Index View
Index.cshtml
- @{
- ViewBag.Title = "Index";
- }
-
- <h2>Index</h2>
-
- @using (Html.BeginForm("Index", "Employee", FormMethod.Post))
- {
- @Html.RadioButton("gender", "Male")<text>Male</text>
- @Html.RadioButton("gender", "Female", true)<text>Female</text>
- <br />
- <input type="submit" value="Submit" />
- }
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!