Introduction

This article shows how to use a RadioButtonFor helper handling HttpPost in MVC applications.

Create an ASP.Net Web Application as in Figure 1.

Figure 1: Web Application

Choose MVC template as in Figure 2.

Figure 2: MVC template

Add an Employee Controller as in Figures 3, 4 and 5.

Figure 3: Add Controller

Figure 4: MVC controller - empty

Figure 5: EmployeeController

EmployeeController.cs

  1. using RadioButtonForApp_MVC.Models;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Web;
  6. using System.Web.Mvc;
  7. namespace RadioButtonForApp_MVC.Controllers
  8. {
  9. public class EmployeeController : Controller
  10. {
  11. //
  12. // GET: /Employee/
  13. public ActionResult Index()
  14. {
  15. Employee emp = new Employee();
  16. return View(emp);
  17. }
  18. [HttpPost]
  19. public string Index(Employee emp)
  20. {
  21. if (string.IsNullOrEmpty(emp.SelectedDepartments))
  22. {
  23. return "You did not select any option";
  24. }
  25. else
  26. return "You selected department is" + emp.SelectedDepartments;
  27. }
  28. }
  29. }
Create an Employee Class as in Figure 6.

Figure 6: Employee

Employee.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. namespace RadioButtonForApp_MVC.Models
  6. {
  7. public class Employee
  8. {
  9. public string SelectedDepartments { get; set; }
  10. public List<Department> Departments
  11. {
  12. get
  13. {
  14. EmployeeEntities db = new EmployeeEntities();
  15. return db.Departments.ToList();
  16. }
  17. }
  18. }
  19. }
Set up Entity Framework as in Figures 7 and 8.

Figure 7: Add ADO.NET Entity Framework

Figure 8: Connection setting

Add the View as in Figures 9 and 10.

Figure 9: Add View

Figure 10: Index View

Index.cshtml

  1. @model RadioButtonForApp_MVC.Models.Employee
  2. @{
  3. ViewBag.Title = "Index";
  4. }
  5. <h2>Index</h2>
  6. @using (Html.BeginForm("Index", "Employee", FormMethod.Post))
  7. {
  8. foreach (var department in Model.Departments)
  9. {
  10. @Html.RadioButtonFor(p => p.SelectedDepartments, department.DepartmentName)@department.DepartmentName
  11. }
  12. <br />
  13. <input type="submit" value="Submit" />
  14. }

The output of the application is as in the following:

Figure 11: Index

Summary

In this article we saw how to use a RadioButtonFor helper handling HttpPost in MVC applications.
Happy coding!