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
  • 47,632
  • 41
  • 144
  • 213

2 Answers2

26
Male: <%= Html.RadioButtonFor(x => x.Gender, "Male") %>
Female: <%= Html.RadioButtonFor(x => x.Gender, "Female") %>
Darin Dimitrov
  • 994,864
  • 265
  • 3,241
  • 2,902
  • 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:` 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