Use checkboxes to add and remove items from a list

Viewed 103

I'm working with asp.net core mvc and I have two views, one to edit a profile and another to show the profile. The view to edit the profile has checkboxes and the view to show the profile has a list with the items that got selected in the edit view. Whenever I edit the profile, all the checkboxes are unselected. I want that whenever I'm on the EditProfile view, the items that were on the ShowProfile view get selected and the others unselected. If I select a checkbox, that item gets added to the list and if I unselect a previous selected item, that item gets removed from the list. Since I'm a beginner, I have no idea how to do this working with both views. I did multiple things and it didn't work

Part of the ShowProfile view

@model ModifyProfile
@{
}
<div class="card">
 <div class="card-body">
  <a class="btn btn primary"href="\ProfileDetails\EditProfile">Edit</a>
 </div>
</div>

<div class="card-body">
 <h3 class="mb-3">Interests</h3>
  <div class="mb-3">
   <div class="text">Interests:</div>
    @if (Model.InterestProfile != null){
     <ul>
      @foreach(InterestProfile interestProfile in Model.InterestProfiles{
        <li class="mb-3">
         @interestProfile.Interest.InterestName
        </li>
                          }
      </ul>
    }else
         {
          @:No interests
         }
  </div>
 </div>

Part of the EditProfileView


@model ProfileViewModel

@{
}

<form action="EditProfile" method="post">
 <div class="card">
  <div class="card-body">
   <button class="btn btn-primary" type="submit">Submit changes</button>
    </div>
     </div>
      <div class="card">
       <div class="card-body">
        <div>
         <label class="form-label">Interested in</label>
          <div class="checkbox">
           @foreach (Interest interest in Model.Interests)
            {
              <label><input type="checkbox" name="interestId" value="@interest.InterestId"> 
               @interest.InterestName </label>
            }
          </div>
        </div>
       </div>
      </div>

Is there a way to do it with checkboxes? I think that a dropdown list could be helpful here but I don't know if it's worth deleting all the code I have already to make that change

0 Answers
Related