Search code examples
asp.net-mvcrazorcheckedradiobuttonfor

MVC Razor RadioButtonFor: How to have NO preset @checked?


@for (var b = 0; b < 11; b++)
  {
    @Html.RadioButtonFor(model => Model.LikelyToReturn, @b, new { @checked = false })
  }

If I leave out

new { @checked = false }

then the first radio button is checked by default. If I include it, the last is checked by default. How would I have NONE of them checked by default?

EDIT AFTER:

This is the model:

public class PatientSatisfactionSurveyPage : Page
{
   //non important stuff removed
   public int LikelyToReturn { get; set; }
   public PatientSatisfactionSurveyPage() { }
}

Solution

  • I was able to reproduce this with my own testing.

    The reason the last radio button is selected is because of your checked = false. The presence of the checked attribute means that the radio button is supposed to be checked. You could have something like checked = "casey-is-awesome!" and one of the radio buttons in the group would be selected.

    If you don't want any of the button selected then simply omit the checked attribute entirely. If you're still having issues please post your model and any related controller code.

    Edit

    Change

    public int LikelyToReturn { get; set; }

    to

    public int? LikelyToReturn { get; set; }.

    int has a default value of 0. Since 0 is being used as the value of the first radio button, the ASP.NET MVC framework is automatically marking it as selected since that value matches the value in the model. By switching to a nullable int the default value will be null and thus the framework won't automatically mark it selected