asp.net-coremodel-view-controllerradio-button

How do I make a HTML.RadioButtonfor be checked by default


I have a Visual Studio, .NET 8 Razor project. I have a model that has a few bool properties. The page works like it should with one exception. I can not get the radio false buttons to be checked by default.

Here is the partial model:

    public bool liveOnProperty { get; set; } = false;
    public bool livingAlone { get; set; } = false;
    public bool militaryService { get; set; } = false;
    public bool ownProperty {get; set; } = false;

Here is the partial view:

<div class="row">
    <div class="col-lg-4 pb-3 text-start">
        <div class="row">
            <div class="col-lg-12">
            <label> Is client living alone?</label>      
            <div class="col-lg-12">
               @Html.RadioButtonFor(model => model.livingAlone, true, new { @class = "control-label col-md-2" })Yes
            </div>
           <div class="col-lg-12">
             @Html.RadioButtonFor(model => model.livingAlone, false, new { @class = "control-label col-md-2", @checked = "true" }) No
           </div>   
        </div>  
    </div>
</div>

I have also tried using

Html.RadioButton(model => model.livingAlone, true)

The value does change the model value from false to true and true to false. Of everything I have seen, the way I am doing it is the way to do it but it is not working.

Is there a different way of doing it?


Solution

  • Maybe you have not initialized the model in the backend and pass it to view. Assume your view is Index.cshtml, your model is named Test, be sure you have similar code like below:

    public IActionResult Index()
    {
        return View(new Test());
    }
    

    Another way is that you can use @Html.RadioButton(string name, object value, bool isChecked, object htmlAttributes) which is no need initialize:

    @Html.RadioButton("livingAlone", true, false, new { @class = "control-label col-md-2" }) Yes
    @Html.RadioButton("livingAlone", false, true, new { @class = "control-label col-md-2" }) No