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?

Larsenal
  • 49,878
  • 43
  • 152
  • 220

2 Answers2

26
Male: <%= Html.RadioButtonFor(x => x.Gender, "Male") %>
Female: <%= Html.RadioButtonFor(x => x.Gender, "Female") %>
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 3
    That's pretty basic, but I'd argue that a proper use would include – Larsenal Apr 07 '10 at 16:12
  • 12
    Expanding on @Larsenal's comment, you can do so like this:`<%= Html.Label("Gender1", "Male:")%><%= Html.RadioButtonFor(x => x.Gender, "Male", new {@id="Gender1"}) %>` – JustinP8 Mar 17 '11 at 18:00
  • Upvoted @JustinP8 and downvoated the answer - two radiobuttonfor's without the @id= give the same id for two html elements which is really nasty! – Andiih Apr 14 '11 at 09:00
  • To add to JustinP8's comment, note that setting the id like this won't work properly with nested models. – JT. May 14 '11 at 05:01
5

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

Community
  • 1
  • 1
Mac
  • 2,312
  • 14
  • 25