In this article I will explain with an example, how to populate (bind) RadioButtonList from database using Entity Framework Code First Approach in ASP.Net MVC Razor.
Note: If you want to learn about populating RadioButtonList using Entity Framework Database First Approach, please refer my article Populate (Bind) RadioButtonList from Database using Entity Framework in ASP.Net MVC.
 
 
Configuring Database with Entity Framework Code First Approach
I have made use of the following table Customers with the schema as follows. CustomerId is an Auto-Increment (Identity) column.
ASP.Net MVC: Populate (Bind) RadioButtonList using Entity Framework Code First Approach
 
I have already inserted few records in the table.
ASP.Net MVC: Populate (Bind) RadioButtonList using Entity Framework Code First Approach
 
Note: You can download the database table SQL by clicking the download link below.
        Download SQL file
 
You will need to configure and connect to the existing database table using Entity Framework Code First Approach.
Note: For more details, please refer my article ASP.Net MVC: EntiyFramework Code First approach with Existing Database.
 
Below is the generated DbContext class.
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
 
public partial class CodeFirstDBContext : DbContext
{
    public CodeFirstDBContext()
        : base("name=CodeFirst")
    {
    }
 
    public virtual DbSet<Customer> Customers { get; set; }
 
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Customer>()
            .Property(e => e.Name)
            .IsUnicode(false);
 
        modelBuilder.Entity<Customer>()
            .Property(e => e.Country)
            .IsUnicode(false);
    }
}
 
 
Controller
The Controller consists of following two Action methods.
Action method for handling GET operation
Inside this Action method, the GetCustomers method is called.
Inside the GetCustomers method, the records are fetched from the Customers table using Entity Framework Code First Approach and are copied into Generic list of SelectListItem class and returned to the View.
Note: The SelectListItem class which is an in-built ASP.Net MVC class. It has all the properties needed for populating a RadioButtonList.
 
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 posted value is captured through the customer parameter which is also set as the Name of the RadioButtonList.
Then the GetCustomers method is called and the selected Customer is fetched using Lambda expression.
Finally, the Name value of the selected Customer 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
{
    // GET: Home
    public ActionResult Index()
    {
        return View(GetCustomers());
    }
 
    [HttpPost]
    public ActionResult Index(string customer)
    {
        var selectedCustomer = GetCustomers().Find(p => p.Value == customer);
        if (selectedCustomer != null)
        {
            selectedCustomer.Selected = true;
            ViewBag.Message = "Selected Customer: " + selectedCustomer.Text;
        }
 
        return View(GetCustomers());
    }
 
    private static List<SelectListItem> GetCustomers()
    {
        using (CodeFirstDBContext context = new CodeFirstDBContext())
        {
            List<SelectListItem> customerList = (from p in context.Customers
                                                 select new SelectListItem
                                                 {
                                                     Text = p.Name,
                                                     Value = p.CustomerId.ToString()
                                                 }).ToList();
 
            return customerList;
        }
    }
}
 
 
View
Inside the View, in the very first line Generic list of 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.
Also there is a Submit Button which when clicked, the Form gets submitted and the value of the selected RadioButton is sent to the Controller.
Finally, the selected Customer 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>
</head>
<body>
    @using (Html.BeginForm("Index", "Home", FormMethod.Post))
    {
        <table>
            @foreach (var m in Model)
            {
                <tr>
                    <td>
                        @Html.RadioButton("Customer", 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
ASP.Net MVC: Populate (Bind) RadioButtonList using Entity Framework Code First Approach
 
 
Downloads