How to bind RadioButton using Enum in Asp.Net MVC
For binding RadioButton using Enum in Asp.Net MVC, we have to follow the following steps:-
Step1: First create the Model class say 'RegisterationModel' in the Models Folder for the RadioButtons.
Example:
public class RegisterationModel
{
public RadioOptions category { get; set; }
public enum RadioOptions
{
General = 1,
SC = 2,
ST = 3,
OBC = 4
}
}
Note=> public RadioOptions category { get; set; } will hold the value of the selected RadioButton.
Step 2: Now in the View i.e. .cshtml File bind these enum values to the RadioButtons.
Example:
@Html.RadioButtonFor(model => model.category, Training_Task.Models.RegisterationModel.RadioOptions.General)
@Html.RadioButtonFor(model => model.category, Training_Task.Models.RegisterationModel.RadioOptions.SC)
@Html.RadioButtonFor(model => model.category, Training_Task.Models.RegisterationModel.RadioOptions.ST)
@Html.RadioButtonFor(model => model.category, Training_Task.Models.RegisterationModel.RadioOptions.OBC)
This will create the RadioButtons for entries in the enum RadioOptions. But to create the label field with each RadioButton
write the following code.
@Html.RadioButtonFor(model => model.category, Training_Task.Models.RegisterationModel.RadioOptions.General) @Html.Label("General")
@Html.RadioButtonFor(model => model.category, Training_Task.Models.RegisterationModel.RadioOptions.SC) @Html.Label("SC")
@Html.RadioButtonFor(model => model.category, Training_Task.Models.RegisterationModel.RadioOptions.ST) @Html.Label("ST")
@Html.RadioButtonFor(model => model.category, Training_Task.Models.RegisterationModel.RadioOptions.OBC) @Html.Label("OBC")
This will create the RadioButtons along with the label corresponding to each RadioButton. The value of the selected RadioButton
can be retrieved from the category variable in the Controller.
The RadioButtons will look like:
Hope it helps...!
0 Comment(s)