How can I bind a list of radioes with dynamic binding?

393 Views Asked by At

I wanna bind a list of controls in my controller.

I don't have any problem with text box, check box or drop down.

For instance,

@Html.TextBox("tblContactPhones[0].description")
@Html.DropDownList("tblContactPhones[0].phoneLable", PhoneType)
@Html.TextBox("tblContactPhones[1].description")
@Html.DropDownList("tblContactPhones[1].phoneLable", PhoneType)

These have same names that bind dynamically in my controller.

public virtual ActionResult Create(tblContact entity)

as u see these names aren't same

but I cant do this for a radio group.

they have to have same names for correct selecting.

and I can't bind this in a list.

any ideas ?

1

There are 1 best solutions below

2
On

You doesn't need to worry about names.

As the main overloads of the @Html.RadioButton() helper are the following:

@Html.RadioButton(string name, object value)
@Html.RadioButton(string name, object value, bool isChecked)

So:

1) if you want 2 rdoBtns as a true/false fashion:

@Html.RadioButton("IsSomething", true)
@Html.RadioButton("isSomething", false)

2) If you have a collection of values - for example an enum:

@Html.RadioButton("FavoriteItem", MyEnum.Item1)
@Html.RadioButton("FavoriteItem", MyEnum.Item2)
@Html.RadioButton("FavoriteItem", MyEnum.Item3)
@Html.RadioButton("FavoriteItem", MyEnum.Item4)

Note that you can pass a true value as the 3rd parameter to the helper to indicate that item should be checked by default:

// This rdo is selected by default
@Html.RadioButton("FavoriteItem", MyEnum.Item1, true) 
@Html.RadioButton("FavoriteItem", MyEnum.Item2)
// other rdoBtns ...