0

I have an MVC application where a user can add and delete to their schedule. Each time they do, it refreshes so the previously selected dropdown goes back to the first option. How do I get it to retain what is selected?

<script>
  $(document).ready(function () {
    for (var a = 0; a < @Model.OnCampusSchedules.Count; a++) {
      let buildingSelectId = '#BuildingSelect_' + a;
      let roomSelectId = '#RoomSelect_' + a;
      var roomValue = '@Model.OnCampusSchedules[c].Room';

       $(buildingSelectId).change(function () {
         var selectedBuilding = $(this).val();

         let id = roomSelectId;
         let roomSelect = $(id);
         console.log(roomSelect);

         let room = roomValue;

         $(roomSelect).empty();

         roomSelect.addClass('spinner').prop('disabled', true);

         $.ajax({
           url: '@Url.Action("GetRoomNumbers", "External")',
           type: 'GET',
           data: {
             building: selectedBuilding,
           },
           success: function (data) {
             if (data.length > 0) {
               $(data).each(function (index, item) {
                 roomSelect.append('<option value="' + item + '"' + (item === room ? 'selected="selected"' : '') + '>' + item + '</option>');
               });
               roomSelect.prop('disabled', false);
             }
           },
           error: function () {
             console.error("Failed to get rooms");
           },
           complete: function () {
             roomSelect.removeClass('spinner');
          }
        });
      }).change();
    }
  });
</script>  
1
  • 2
    If the option is deleted is normal to do refresh and pick a default option.... in general the first one. What is your expected behavior?
    – D A
    Commented Jun 18 at 7:23

0

Browse other questions tagged or ask your own question.