9

I have a seemingly easy task of setting a radio button "checked" based on model's boolean value. I have a boolean in my model "IsSDPDonor" which I want to use it for Yes/No Radio buttons. The "Yes" radio button should be checked if "IsSDPDonor" is true and "No" radio button when it is false. I tried to use the code below but it always checks the "No" radio button.

 @Html.Label("Would You Like to Donate Platelets (SDP)") : 
 @Html.RadioButtonFor(m => m.Donor.IsSDPDonor, true, new {@checked = Model.Donor.IsSDPDonor ? "checked" : ""}) Yes 
 @Html.RadioButtonFor(m => m.Donor.IsSDPDonor, false, new { @checked = !Model.Donor.IsSDPDonor ? "checked" : "" }) No

I was getting a little frustrated, so I thought that I would rather take some help. Basically, the HTML syntax says to put only the "Checked" attribute without any values to check a radio button. I was wondering how would I do that using MVC3 razor syntax.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
Jatin
  • 4,023
  • 10
  • 60
  • 107
  • 1
    why are using `@checked` instead of `checked` in the anonymous object definition? also, using the `checked="checked"` should have the same effect as the checked without values, with less compatibility issues – smartcaveman Nov 13 '11 at 13:53
  • 1
    @smartcaveman because `checked` is a keyword you have to use the `@` to distinguish it as a variable (property name, in this case). – tvanfosson Nov 13 '11 at 14:23

1 Answers1

14

Create the HTML options in a code block, leaving them null if the button shouldn't be checked, then use the proper variable in your helper.

@{
    var yesOptions = Model.Donor.IsSDPDonor ? new { @checked = "checked" } : null;
    var noOptions =  Model.Donor.IsSDPDonor ? null : new { @checked = "checked" };
}
@Html.Label("Would You Like to Donate Platelets (SDP)") : 
@Html.RadioButtonFor(m => m.Donor.IsSDPDonor, true, yesOptions ) Yes 
@Html.RadioButtonFor(m => m.Donor.IsSDPDonor, false, noOptions ) No

EDIT: After looking at the source code, it appears to me that it should be setting this property based on the value of the model. Have you tried omitting the HTML attributes completely?

case InputType.Radio:
    if (!usedModelState) {
        string modelStateValue = htmlHelper.GetModelStateValue(name, typeof(string)) as string;
        if (modelStateValue != null) {
            isChecked = String.Equals(modelStateValue, valueParameter, StringComparison.Ordinal);
            usedModelState = true;
        }
    }
    if (!usedModelState && useViewData) {
        isChecked = htmlHelper.EvalBoolean(name);
    }
    if (isChecked) {
        tagBuilder.MergeAttribute("checked", "checked");
    }
    tagBuilder.MergeAttribute("value", valueParameter, isExplicitValue);
    break;
tvanfosson
  • 524,688
  • 99
  • 697
  • 795
  • Thanks for pointing that out in your update. Indeed we don't need any html attributes in this case. It just works. Great. Thanks again. – Jatin Nov 13 '11 at 14:19