Applying a class to RadioButtonFor

842 Views Asked by At

I am applying a class to RadioButtonFor so that the width between radio button and label won't be too big. Without the class, the radio button has a large space to its left and right as shown below. However, when I apply the class, only the radio button that is currently selected gets the white space removed (see "Tell You Later" option in image below) because of the if condition used. How can I apply the class to all radio buttons ? I tried making the following change to the code, the problem is that even though this method applied the class to all radio buttons, the radio button selection saved on database is not applied to correct radio button. With the following method, the last radio button is always selected: item.IsChecked == true ? new { @checked = "checked", @class = "myclassradio" } : new { @checked = "unchecked", @class = "myclassradio"}

enter image description here

My complete code below:

@foreach (var item in Model.religion)
{                        
   <span>@Html.RadioButtonFor(m => m.SelectedReligion, item.ID, item.IsChecked == true ? new { @checked = "checked", @class = "myclassradio" } : null ) @item.MyReligion </span>    
}
1

There are 1 best solutions below

0
sonnyk2016 On

I figured it out. Just put an IF condition inside the foreach loop....duh?!!

@foreach (var item in Model.religion)
    if ( item.IsChecked == true )  
    {                     
        <span>@Html.RadioButtonFor(m => m.SelectedReligion, item.ID, new { @checked = "checked", @class = "myclassradio" } ) @item.MyReligion </span>    
    }
    else
    {
        <span>@Html.RadioButtonFor(m => m.SelectedReligion, item.ID, new { @class = "myclassradio" } ) @item.MyReligion </span>    
    }
}