Home > Software design >  Change from checkbox to radio buttons
Change from checkbox to radio buttons

Time:07-01

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 >
     <div >
      @for (int i = 0; i < Model.Count; i  )
       {
      <div >
       <input type="hidden" asp-for="@Model[i].Id" />
        <input type="hidden" asp-for="@Model[i].Name" />
         <input asp-for="@Model[i].Selected"  />
                    <label asp-for="@Model[i].Selected" >
                        @Model[i].Name
                    </label>
      </div>
  }
     </div>
    </div>

CodePudding user response:

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 >
     <div >
      @for (int i = 0; i < Model.Count; i  )
       {
      <div >
       <input type="hidden" asp-for="@Model[i].Id" />
        <input type="hidden" asp-for="@Model[i].Name" />
        <label asp-for="@Model[i].Selected" >
                        @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>
  • Related