RadioButton control in MVC
Here I am explaining how to create RadioButton Control in MVC and get the selected radio button reference.
<%@ 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.
After selecting the choice when you press the submit button, the browser will show you the value of the selected radio button.
Leave Comment