In this article I will explain with an example, how to implement RadioButton Group using Html.RadioButton Helper method in ASP.Net MVC Razor.
The RadioButtons will be populated from Database by looping through the Model.
The RadioButtons are grouped by specifying common name for all RadioButtons in ASP.Net MVC Razor.
Database
This article makes use of a table named Fruits whose schema is defined as follows.
The Fruits table has the following records.
Note: You can download the database table SQL by clicking the download link below.
Namespaces
You will need to import the following namespaces.
using System.Configuration;
using System.Data.SqlClient;
using System.Collections.Generic;
Model
This article uses SelectListItem class as Model which is an in-built ASP.Net MVC class. It has all the properties needed for populating a RadioButtonList.
Controller
The Controller consists of two Action methods.
Action method for handling GET operation
Inside this Action method, the PopulateFruits method is called.
Inside the PopulateFruits method, the records from the Fruits table are fetched using DataReader and generic list of SelectListItem class is populated.
The FruitName is stored in the Text property while the FruitId is stored in the Value property.
Finally the list of Fruits are returned to the View.
Action method for handling POST operation
This Action method handles the call made from the POST function from the View.
When the Form is submitted, the ID of selected Fruit is captured in the Fruit parameter.
Then the PopulateFruits method is called and the selected Fruit is fetched using Lambda expression and it is set into a ViewBag object which will be later displayed in View using JavaScript Alert Message Box.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
List<SelectListItem> items = PopulateFruits();
return View(items);
}
[HttpPost]
public ActionResult Index(string fruit)
{
List<SelectListItem> items = PopulateFruits();
var selectedItem = items.Find(p => p.Value == fruit);
if (selectedItem != null)
{
selectedItem.Selected = true;
ViewBag.Message = "Selected Fruit: " + selectedItem.Text;
}
return View(items);
}
private static List<SelectListItem> PopulateFruits()
{
List<SelectListItem> items = new List<SelectListItem>();
string constr = ConfigurationManager.ConnectionStrings["Constring"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = " SELECT FruitName, FruitId FROM Fruits";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
while (sdr.Read())
{
items.Add(new SelectListItem
{
Text = sdr["FruitName"].ToString(),
Value = sdr["FruitId"].ToString()
});
}
}
con.Close();
}
}
return items;
}
}
View
Inside the View, in the very first line the SelectListItem class is declared as Model for the View.
The View consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.
ActionName – Name of the Action. In this case the name is Index.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
Inside the Form, a loop is executed over the generic list of SelectListItem class objects and an HTML Table is generated consisting of a RadioButton and Label elements generated using the following HTML helper methods.
Html.RadioButton – The first parameter is the name of the RadioButton which is hardcoded because it should be same for all RadioButtons so that they operate in Group. The second parameter is the value of the RadioButton, the third parameter is used for checking/unchecking the RadioButton and finally in the fourth parameter, the ID attribute of the RadioButton is set to its Value so that it is unique.
Html.Label – The first parameter is the Text to be displayed in the Label element while the FOR attribute is set to the value of the RadioButton so that when the Label is clicked the RadioButton is checked.
When the Submit Button is clicked, the Form gets submitted and the value of the selected RadioButton is sent to the Controller.
Finally the selected Fruit name is displayed using JavaScript Alert Message Box.
@model List<SelectListItem>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
<style type="text/css">
body {
font-family: Arial;
font-size: 10pt;
}
</style>
</head>
<body>
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
<table>
@foreach(var m in Model)
{
<tr>
<td>
@Html.RadioButton("Fruit", m.Value, m.Selected, new {@id = m.Value })
</td>
<td>
@Html.Label(m.Text, new { @for = m.Value})
</td>
</tr>
}
</table>
<br/>
<input type="submit" value="Submit"/>
}
@if (ViewBag.Message != null)
{
<script type="text/javascript">
window.onload = function () {
alert("@ViewBag.Message");
};
</script>
}
</body>
</html>
Screenshot
Downloads