Search code examples
htmlasp.netasp.net-mvcasp.net-coremodel-view-controller

Change from checkbox to radio buttons


I have a simple web app on asp.net core mvc with a view that has checkboxes and I want to change that to use radio buttons instead but there's a for loop there and I can't make it work because of that. From what I tried, or the radio buttons get all selected or none gets selected and there should be one specific selected

@model List<ChangeItemViewModel>

<form method="post">
    <div class="card">
     <div class="card-body">
      @for (int i = 0; i < Model.Count; i++)
       {
      <div class="form-check">
       <input type="hidden" asp-for="@Model[i].Id" />
        <input type="hidden" asp-for="@Model[i].Name" />
         <input asp-for="@Model[i].Selected" class="form-check-input" />
                    <label asp-for="@Model[i].Selected" class="form-check-label">
                        @Model[i].Name
                    </label>
      </div>
  }
     </div>
    </div>


Solution

  • You can try to check the value of @Model[i].Selected,and use two radio buttons to replace one checkbox:

    @model List<ChangeItemViewModel>
    
    <form method="post">
        <div class="card">
         <div class="card-body">
          @for (int i = 0; i < Model.Count; i++)
           {
          <div class="form-check">
           <input type="hidden" asp-for="@Model[i].Id" />
            <input type="hidden" asp-for="@Model[i].Name" />
            <label asp-for="@Model[i].Selected" class="form-check-label">
                            @Model[i].Name
                        </label>
            @if (Model.list[i].Selected)
        {
            
            <input type="radio" value=true name="list[@i].Selected" checked><label>true</label>
            <input type="radio" value=false name="list[@i].Selected"><label>false</label>
        }
        else
        {
            
            <input type="radio" value=true name="list[@i].Selected"><label>true</label>
            <input type="radio" value=false name="list[@i].Selected" checked><label>false</label>
        }
            
                        
          </div>
      }
         </div>
        </div>