RadioButtonFor in ASP.NET MVC 2
Asked Answered
F

2

15

Can someone provide a simple example of how to properly use Html.RadioButtonFor? Let's say it's a simple scenario where my model has a string property named Gender. I want to display two radio buttons: "Male" and "Female".

What is the most clean way to implement this while retaining the selected value in an Edit view?

Feingold answered 6/4, 2010 at 22:6 Comment(0)
B
5

This question on StackOverflow deals with RadioButtonListFor and the answer addresses your question too (@Larsenal it also includes labels with the "for" attribute)

Butacaine answered 11/4, 2010 at 21:35 Comment(0)
G
26
Male: <%= Html.RadioButtonFor(x => x.Gender, "Male") %>
Female: <%= Html.RadioButtonFor(x => x.Gender, "Female") %>
Guanabana answered 7/4, 2010 at 6:36 Comment(4)
That's pretty basic, but I'd argue that a proper use would include <label> tags with a "for" attribute matching it to a radio button.Feingold
Expanding on @Larsenal's comment, you can do so like this:<%= Html.Label("Gender1", "Male:")%><%= Html.RadioButtonFor(x => x.Gender, "Male", new {@id="Gender1"}) %>Sternpost
Upvoted @Sternpost and downvoated the answer - two radiobuttonfor's without the @id= give the same id for two html elements which is really nasty!Draff
To add to JustinP8's comment, note that setting the id like this won't work properly with nested models.Karlow
B
5

This question on StackOverflow deals with RadioButtonListFor and the answer addresses your question too (@Larsenal it also includes labels with the "for" attribute)

Butacaine answered 11/4, 2010 at 21:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.