Introduction
In ASP.NET MVC, a Radio Button is used when we want the user to select only ONE option from multiple choices.
π Example:
1. What is Radio Button in MVC?
Radio button allows:
β Only one selection
β Easy and clear choice
Html Helper:
@Html.RadioButtonFor()
2. Why We Use Radio Button?
We use radio buttons when:
π Checkbox = multiple select
π Radio Button = single select
3. Static Radio Button (Manual Data)
Model
public class Student
{
public string Gender { get; set; }
}
View
@model Student
@Html.RadioButtonFor(m => m.Gender, "Male") Male
@Html.RadioButtonFor(m => m.Gender, "Female") Female
@Html.RadioButtonFor(m => m.Gender, "Other") Other
Explanation
4. Dynamic Radio Button (From SQL Server)
Step 1: Table Example
Gender Table
------------
Id Name
1 Male
2 Female
3 Other
Step 2: Model
public class Gender
{
public int Id { get; set; }
public string Name { get; set; }
}
ViewModel
public class StudentViewModel
{
public int SelectedGender { get; set; }
public List<Gender> Genders { get; set; }
}
Step 3: Controller
public ActionResult Create()
{
StudentViewModel model = new StudentViewModel();
using (MyDbContext db = new MyDbContext())
{
model.Genders = db.Genders.ToList();
}
return View(model);
}
Step 4: View
@model StudentViewModel
@foreach (var item in Model.Genders)
{
<div>
<input type="radio"
name="SelectedGender"
value="@item.Id" /> @item.Name
</div>
}
Step 5: POST Method
[HttpPost]
public ActionResult Create(StudentViewModel model)
{
int selectedId = model.SelectedGender;
return View();
}
Explanation
5. Set Selected Radio Button
@Html.RadioButtonFor(m => m.Gender, "Male", new { @checked = "checked" })
OR using model:
model.Gender = "Male";
6. jQuery with Radio Button
Get Selected Value
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$("input[name='SelectedGender']").change(function () {
var value = $(this).val();
console.log("Selected: " + value);
});
</script>
Explanation
7. Custom Radio Button (Static + Dynamic)
View
<div>
<input type="radio" name="SelectedGender" value="0" /> Select None
</div>
@foreach (var item in Model.Genders)
{
<div>
<input type="radio"
name="SelectedGender"
value="@item.Id" /> @item.Name
</div>
}
Explanation
First option = static
Others = from database
Only one can be selected
8. Important Points
β Same name is required
β Use ViewModel for dynamic data
β Radio button allows single selection
β Use jQuery for events
9. Common Mistakes
β Different name for radio buttons
β Not binding with model
β Forgetting to set value
β Using checkbox instead of radio
10. Conclusion
Radio Button is very useful when only one option is required.
You learned: