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?
The following seems shorter way to achieve the same:
Possible scenarios when rendering the view:
Test_Emne = null=> none of the radios is checkedTest_Emne = true=> the first radio is checkedTest_Emne = false=> the second radio is checkedPossible scenarios when posting back:
Test_Emneproperty will be set tonullTest_Emneproperty will be set totrueTest_Emneproperty will be set tofalseUPDATE:
This could be extended to any property and any numbers of radio buttons. For example:
and then:
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.