ASP.Net Core MVC: Populate (Bind) RadioButtonList from Database using Entity Framework

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:

  1. Create a database model for the data that you want to bind to the RadioButtonList.
  2. Use Entity Framework to retrieve data from the database and store it in a list.
  3. In the controller, create a method that retrieves the data from the database using Entity Framework.
  4. Pass the data to the view as a model.
  5. In the view, use a Razor loop to iterate through the data and generate the RadioButtonList options.
  6. 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:

  1. Database Model

public class Gender
{
    public int Id { get; set; }
    public string Name { get; set; }
}

 

  1. Controller Method

public IActionResult Index()
{
    List<Gender> genders = _context.Genders.ToList();
    return View(genders);
}

 

  1. 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.

Leave a Comment