1

Currently i am creating two buttons and setting the selected value this way:

@if (Model.Test_Emne == null)
{
    @Html.RadioButtonFor(x => x.Test_Emne, 1) <span>Ja</span>
    <br />
    @Html.RadioButtonFor(x => x.Test_Emne, 0) <span>Nej</span>

}

@if (Model.Test_Emne == true)
{
    @Html.RadioButtonFor(x => x.Test_Emne, 1, new { @checked = "checked" }) <span>Ja</span>
    <br />
    @Html.RadioButtonFor(x => x.Test_Emne, 0) <span>Nej</span>
} else if (Model.Test_Emne == false)
{
    @Html.RadioButtonFor(x => x.Test_Emne, 1) <span>Ja</span>
    <br />
    @Html.RadioButtonFor(x => x.Test_Emne, 0, new { @checked = "checked" }) <span>Nej</span>
}

I have a lot of radio buttons on my page, so i am looking for a way to do this with less code.

I have also seen:

Has anyone implement RadioButtonListFor<T> for ASP.NET MVC?
and
http://jonlanceley.blogspot.com/2011/06/mvc3-radiobuttonlist-helper.html


Are these the only options?

Community
  • 1
  • 1
Kenci
  • 4,794
  • 15
  • 64
  • 108

1 Answers1

2

The following seems shorter way to achieve the same:

@Html.RadioButtonFor(x => x.Test_Emne, true) <span>Ja</span>
<br />
@Html.RadioButtonFor(x => x.Test_Emne, false) <span>Nej</span>

Possible scenarios when rendering the view:

  • Test_Emne = null => none of the radios is checked
  • Test_Emne = true => the first radio is checked
  • Test_Emne = false => the second radio is checked

Possible scenarios when posting back:

  • If none of the radios is checked the Test_Emne property will be set to null
  • If the first radio is checked the Test_Emne property will be set to true
  • If the second radio is checked the Test_Emne property will be set to false

UPDATE:

This could be extended to any property and any numbers of radio buttons. For example:

public string Foo { get; set; }

and then:

@Html.RadioButtonFor(x => x.Foo, "value1") <span>Foo 1</span>
@Html.RadioButtonFor(x => x.Foo, "value2") <span>Foo 2</span>
@Html.RadioButtonFor(x => x.Foo, "value3") <span>Foo 3</span>
@Html.RadioButtonFor(x => x.Foo, "value4") <span>Foo 4</span>
...

and then depending of the value of the Foo property the corresponding radio button will be selected. For example if you set model.Foo = "value3"; the third radio will be preselected.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • This works very nice with booleans. Thanks! Is there a similar approach, when i have five radio buttons that have a value from 1-5, and the selected button should be the one which has the same value as a property (ie. property name: Bes_Af_Value) ? – Kenci Mar 14 '12 at 13:10
  • 1
    @Kenci, of course. This works with any type you want. I have updated my answer with an example. – Darin Dimitrov Mar 14 '12 at 13:12