In this article I will explain with an example, how to implement RadioButtons (RadioButtonList) in ASP.Net Core MVC.
The records from the Database will be fetched from Database Table using ADO.Net into SelectListItem class as Model and a Custom RadioButtonList has been populated in ASP.Net Core MVC.
The RadioButtons are grouped by specifying common name for all RadioButtons in ASP.Net Core MVC.
Note: For beginners in using ADO.Net with ASP.Net Core MVC, please refer my article .Net Core: ADO.Net Tutorial with example.
 
 
Database
This article makes use of a table named Fruits whose schema is defined as follows.
ASP.Net Core MVC: RadioButtons (RadioButtonList) example
 
The Fruits table has the following records.
ASP.Net Core MVC: RadioButtons (RadioButtonList) example
 
Note: You can download the database table SQL by clicking the download link below.
          Download SQL file
 
 
Model
This article uses SelectListItem class as Model which is an in-built ASP.Net Core MVC class. It has all the properties needed for populating a RadioButtonList.
 
 
Namespaces
You will need to import the following namespaces.
using System.Data.SqlClient;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc.Rendering;
 
 
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 Submit Button is clicked.
When the Form is submitted, the FruitId 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.
Note: For more details on displaying message using JavaScript Alert MessageBox, please refer my article ASP.Net MVC: Display Message from Controller in View using JavaScript Alert MessageBox.
 
public class HomeController : Controller
{
    public IActionResult Index()
    {
        List<SelectListItem> items = PopulateFruits();
        return View(items);
    }
 
    [HttpPost]
    public IActionResult 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()
    {
        string constr = @"Data Source=.\SQL2019;Initial Catalog=AjaxSamples;Integrated Security=true";
        List<SelectListItem> items = new List<SelectListItem>();
        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 generic list of SelectListItem class is declared as Model for the View.
The View consists of an HTML Form with following ASP.Net Tag Helpers attributes and a Submit Button.
asp-action – Name of the Action. In this case the name is Index.
asp-controller – Name of the Controller. In this case the name is Home.
method – 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 which in turn generates a list containing a group of HTML Label elements and HTML RadioButtons.
Note: The RadioButtons are grouped by keeping the Name attribute value constant for all RadioButtons.
 
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>
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
    Layout = null;
}
 
<!DOCTYPE html>
 
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <form method="post" asp-controller="Home" asp-action="Index">
        @foreach (var fruit in Model)
        {
            <input id="@fruit.Value" type="radio" name="Fruit" value="@fruit.Value"/>
            <label for="@fruit.Value">@fruit.Text</label>
            <br/>
        }
        <br/>
        <input type="submit" value="Submit"/>
    </form>
    @if (ViewBag.Message != null)
    {
        <script type="text/javascript">
            window.onload = function () {
                alert("@ViewBag.Message");
            };
        </script>
    }
</body>
</html>
 
 
Screenshot
ASP.Net Core MVC: RadioButtons (RadioButtonList) example
 
 
Downloads