ASP.Net Core MVC: Populate (Bind) RadioButtonList from Database using Entity Framework
In this article, we will discuss ASP.Net Core MVC: Populate (Bind) RadioButtonList from Database using Entity Framework. I will use the visual studio 2019 framework and SQL server 2022 for this demo.
To populate a RadioButtonList in ASP.NET Core MVC from a database using Entity Framework, you can follow these steps:
- Create a database model for the data that you want to bind to the RadioButtonList.
- Use Entity Framework to retrieve data from the database and store it in a list.
- In the controller, create a method that retrieves the data from the database using Entity Framework.
- Pass the data to the view as a model.
- In the view, use a Razor loop to iterate through the data and generate the RadioButtonList options.
- Use the HtmlHelper class to generate the RadioButtonList and bind it to the data.
Here’s an example of the code to achieve the above steps:
-
Database Model
public class Gender { public int Id { get; set; } public string Name { get; set; } }
-
Controller Method
public IActionResult Index() { List<Gender> genders = _context.Genders.ToList(); return View(genders); }
-
View
@model List<Gender> <form asp-controller="Home" asp-action="Index" method="post"> @foreach (var gender in Model) { <input type="radio" name="Gender" value="@gender.Id"> @gender.Name<br> } <input type="submit" value="Submit"> </form>
Note: In this example, we are using a Razor loop to generate the RadioButtonList options, but you can also use the HtmlHelper class to generate the RadioButtonList and bind it to the data.