how to show and use Radio button in Asp.Net MVC3

2019-05-31 22:58发布

问题:

I want to have two radio buttons in my Asp.Net MVC3 App.There is no field in my Database representing these Radio button. So i cant use them this way

 @Html.LabelFor(model => model.Monthly)
 @Html.EditorFor(model => model.Yearly)

I have tried to use this to show my radio button

 @Html.Label("Monthly","Monthly")
 @Html.RadioButton("Monthly","Monthlyy")
 @Html.Label("Yearly","Yearly")
 @Html.RadioButton("Yearly","Yearly")

The buttons are visible but the user can select both the buttons together.Whereas i want that only one button can be checked at a time. Also i would be needing the label of the checked radio button for further functionality of my App.How can i add the radio button and how can i get the label(text value) of the checked radio button.

Please guide how to achieve this.

回答1:

For you to be able to group the radio buttons, they need to have the same name. i.e.

<input type="radio" name="group1" value="No"/>
<input type="radio" name="group1" value="Yes"/>
<input type="radio" name="group2" value="No"/>
<input type="radio" name="group2" value="Yes"/>

So in your case, what you want to do is the following

@Html.Label("Monthly")
@Html.RadioButton("MonthlyOrYearly", "Monthly")
@Html.Label("Yearly")
@Html.RadioButton("MonthlyOrYearly", "Yearly")