In this article I will explain with an example, how to implement RadioButtons (RadioButtonList) in ASP.Net Core Razor Pages.
Group of multiple RadioButtons (RadioButtonList) will be populated from SQL Server Database by looping through the Model.
The RadioButtons are grouped by specifying common name for all RadioButtons in ASP.Net Core Razor Pages.
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.
Model
Following is a Model class named FruitModel with two properties i.e. FruitId and FruitName.
public class FruitModel
{
[BindProperty]
public int FruitId { get; set; }
[BindProperty]
public string FruitName { get; set; }
}
Namespaces
You will need to import the following namespaces.
using System.Data.SqlClient;
using System.Collections.Generic;
Razor PageModel (Code-Behind)
The PageModel consists of two Action Handler methods.
Handler method for handling GET operation
Inside this Handler method, the PopulateFruits method is called.
Inside the PopulateFruits method, the records from the Fruits table are fetched using DataReader and generic list of FruitModel class is populated.
Finally, the list of Fruits is returned.
Handler method for handling Button Click and POST operation
This Handler method handles the POST call when the Submit Button is clicked and the Form is submitted.
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 ViewData object which will be later displayed in View using JavaScript Alert Message Box.
public class IndexModel : PageModel
{
public List<FruitModel> Fruits { get; set; }
public void OnGet()
{
//Populate Model from Database.
this.Fruits = PopulateFruits();
}
public void OnPostSubmit(int fruit)
{
//Populate Model from Database.
this.Fruits = PopulateFruits();
//Fetch the ID and the TEXT value.
string message = "Selected Fruit Id: " + fruit;
message += "\\nFruit Name: " + this.Fruits.Find(p => p.FruitId == fruit).FruitName;
//Set the value in ViewData.
ViewData["Message"] = message;
}
private static List<FruitModel> PopulateFruits()
{
string constr = @"Data Source=.\SQL2019;Initial Catalog=AjaxSamples;Integrated Security=true";
List<FruitModel> fruits = new List<FruitModel>();
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())
{
fruits.Add(new FruitModel
{
FruitName = sdr["FruitName"].ToString(),
FruitId = Convert.ToInt32(sdr["FruitId"])
});
}
}
con.Close();
}
}
return fruits;
}
}
Razor Page (HTML)
The HTML of Razor Page consists of an HTML Form with a Submit Button.
Inside the Form, a loop is executed over the generic List of FruitModel 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.
The Submit Button has been set with the POST Handler method using the asp-page-handler attribute.
Note: In the Razor PageModel, the Handler method name is OnPostSubmit but here it will be specified as Submit when calling from the Razor HTML Page.
When the Submit Button is clicked, the Form gets submitted and the value of the selected RadioButton is sent to the PageModel.
Finally, the selected Fruit name is displayed using JavaScript Alert Message Box.
@page
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@model Razor_RadioButtonList.Pages.IndexModel
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
</head>
<body>
<form method="post">
@foreach (var fruit in Model.Fruits)
{
<input id="@fruit.FruitId" type="radio" name="Fruit" value="@fruit.FruitId"/>
<label for="@fruit.FruitId">@fruit.FruitName</label>
<br/>
}
<br/>
<input type="submit" value="Submit" asp-page-handler="Submit"/>
</form>
@if (ViewData["Message"] != null)
{
<script type="text/javascript">
window.onload = function () {
alert("@ViewData["Message"]");
};
</script>
}
</body>
</html>
Screenshot
Downloads