articles

Home / DeveloperSection / Articles / RadioButton control in MVC

RadioButton control in MVC

RadioButton control in MVC

Chris Anderson 39401 03-Oct-2011

RadioButton control in MVC

Here I am explaining how to create RadioButton Control in MVC and get the selected radio button reference.

Here is an Index View I have created various radio buttons that displays web technologies name by using Html Helper.
In the first parameter of the radio button, I passed the name of radio button and in the second parameter, I have passed its value that is similar to its text.
I have also created a submit button and on click of that submit button we get the value of selected radio button.

 <%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<RadioButtonListMVC.Models.GenModel>" %>  

<!DOCTYPE html>
<html>
<head runat="server">
     <title>Index</title>
</head>
<body>
 <% using (Html.BeginForm("Show","Home",FormMethod.Post)) { %>
     <div><b>Select Technology: </b>
         <%= Html.RadioButton("technology", "ASP.NET") %> ASP.NET
         <%= Html.RadioButton("technology", "PHP") %> PHP
         <%= Html.RadioButton("technology", "JSP") %> JSP
         <%= Html.RadioButton("technology", "ASP.NET MVC") %> ASP.NET MVC
         <br /><br />
         <input type="submit" value="Submit" />
     </div>
     <%} %>
</body>
</html>

After creating a radio button in View, you can retrieve the reference of the selected radio button with the help of the Controller.

Here is a Controller, I have created a Show action that invokes when a submit button is pressed and when Show action invoked

it retrieves the reference of the selected radio button and the store its value in a string and then returns a formatted string.

using System.Web.Mvc;

using RadioButtonListMVC.Models;
namespace RadioButtonListMVC.Controllers
{
     public class HomeController : Controller
    {
         public ActionResult Index()
         {
            return View();
         }
         [AcceptVerbs(HttpVerbs.Post)]
         public string Show(FormCollection form)
         {
            string selectedTechnology = form["technology"];
            return "You have selected a technology: <b>"+selectedTechnology+"</b>";
         }
    }
}

After performing the above task you can see an output in the browser that displays a list of the radio buttons. You can select one of them.

RadioButton control in MVC

After selecting the choice when you press the submit button, the browser will show you the value of the selected radio button.

RadioButton control in MVC

By completing the above process you can simply learn how to create a radio button group or list and how to get selected value from the list of radio buttons in MVC.


Updated 18-Mar-2020
hi I am software developer at mindstick software pvt. ltd.

Leave Comment

Comments

Liked By