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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With