Search code examples
asp.net-mvcrazorasp.net-core-mvc

AspNet core MVC 1.1.3 Default selected radio button


I am trying to default a radio button to be checked.

<div>@Html.RadioButtonFor(m => m.IsActive, "OofDeactive", new { @class = "isActive", @checked="checked"})</div>
<div>@Html.RadioButtonFor(m => m.IsActive, "OofActive", new { @class = "isActive" })</div>

Note that the model contains a property

public bool IsActive { get; set; }

I have found the same issue here but for MVC6 although it is closed: https://github.com/aspnet/Mvc/issues/3098

Is this an issue or am I doing something wrong?


Solution

  • The RadioButtonFor() (as do all the HtmlHelper methods) work by binding to the value of your property and its that value which determines which radio button is checked.

    Your IsActive property is a bool which has only 2 possible values, true and false and cannot bind to string with values of "OofDeactive" or "OofActive". Change the code to

    @Html.RadioButtonFor(m => m.IsActive, true, new { @class = "isActive", id = "" })
    @Html.RadioButtonFor(m => m.IsActive, false, new { @class = "isActive", id = "" })
    

    And if the value of property IsActive is true the first radio button will be selected, otherwise the 2nd will be.

    Note that the RadioButtonFor() method generates duplicate id attributes so either use new { id = "" } to remove the id attribute (or give them a unique id if needed for some other purpose). Setting the checked attribute is pointless since it will be ignored.