Search code examples
javascriptjqueryasp.netajaxasp.net-mvc

I have inputs types of checkbox and when I perform delete or retrieve methods it works but page is not reload


In my Asp.Net Mvc project, I have checkbox type inputs and I get the Ids of items through them by using jquery and send them controller by using ajax. Methods are working but after work the page is not reload so I can see the result only reload page manuel.

function takeIds() {
    var selected = [];
    $('#checkDiv input[type="checkbox"]:checked').each(function () {
        selected.push($(this).attr('value'));
    });

    var messageIds = selected.join(',');
    console.log("messageIds: ", messageIds); // Konsolda messageIds'yi kontrol etmek için

    $.ajax({
        url: '@Url.Action("RetrieveMessage", "WriterPanelMessage")',
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        data: JSON.stringify({ messageIds: messageIds }),
        timeout: 10000,
        success: function (result) {
            console.log("AJAX Success: ", result);
            if (result === 'Ok') {
                location.reload()
            } else {
                alert('Mesaj geri alma işlemi başarısız oldu.');
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            console.error("AJAX Error: ", textStatus, errorThrown);
            alert('Bir hata oluştu.');
        }
    });
}
   [HttpPost]
   public async Task<JsonResult> RetrieveMessage(string messageIds)
   {
       try
       {
           string p = (string)Session["WriterMail"];
           string[] Ids = messageIds.Split(',');
           List<Message> messages = messageManager.GetListInbox(p);

           if (!string.IsNullOrEmpty(messageIds) && Ids.Length > 0)
           {
               foreach (var item in messages)
               {
                   foreach (var id in Ids)
                   {
                       if (item.MessageID == Convert.ToInt32(id))
                       {
                           item.IsDeleted = false;
                           await messageManager.Update(item);
                       }
                   }
               }
           }

           System.Diagnostics.Debug.WriteLine("Yönlendirme yapılacak: DeletedMessages");
           return Json(new { result = "Ok" });
       }
       catch (Exception ex)
       {
           System.Diagnostics.Debug.WriteLine("Hata oluştu: " + ex.Message);
           return Json(new { result = "Fail" });
       }
   }

Solution

  • I did this pretty fast and mocked up the ajax part just to show the action (gives a blank screen after a short delay) if you check something to post.

    Here are some details re: the issue at hand.

    Instance methods

    Instance properties:

    SO given all that info ^^ suggestion is to use window.location.href = window.location.href;

    function takeIds(event) {
      const container = $(this).closest('.message-container');
      const checks = container
        .find('input[type="checkbox"]')
        .filter(':checked');
      let info = `<div>${container.data("postaddress")}</div><div>${( !checks.length ? "Nothing checked!" :
        `Good: ${checks.length} checked!`)}</div>`;
      $('.information')
        .toggleClass('error', !checks.length)
        .html(info);
    
      if (!checks.length) {
        return;
      }
      // could do this or the map only
      //let selected = [];
      //checks.each(function() {
      //   selected.push($(this).val());
      //});
      let selected = checks.map((i, ck) => ck.value).toArray();
      let messageIds = selected;
      $('.information')
        .toggleClass('error', false)
        .html($('.information').html() + `[${messageIds}]`);
      $.ajax({
        url: container.data("postaddress"),
        type: 'POST',
        dataType: 'json',
        data: messageIds,
        timeout: 10000
      }).done(function(result) {
        let msg = `<div>AJAX Success:${JSON.stringify(result)}</div>`;
        if (result.ok) {
          msg = msg + "<div class='error'>We are good here we will reload shortly...</div>";
          setTimeout(() => {
            window.location.href = window.location.href;
          }, 5000);
    
        } else {
          msg = msg + '<div>Mesaj geri alma işlemi başarısız oldu. Woops</div>';
          // alert('Mesaj geri alma işlemi başarısız oldu.');
        }
        $('.information')
          .toggleClass('error', false)
          .html($('.information').html() + msg);
      }).fail(function(jqXHR, textStatus, errorThrown) {
        let msg = `<div>AJAX Error:${textStatus}Error:${errorThrown}</div>`;
        $('.information')
          .toggleClass('error', true)
          .html($('.information').html() + msg);
        // alert('Bir hata oluştu.');
      });
    }
    $('.message-container').on('click', '.testerout', takeIds);
    
    /* below here is my fake ajax mock 
      I did not invent this. Leveraged some info from here https://stackoverflow.com/q/5272698/125981 */
    function mockAjax(options) {
      var that = {
        done: function done(callback) {
          if (options.success)
            setTimeout(callback, options.timeout, options.response);
          return that;
        },
        fail: function error(callback) {
          if (!options.success)
            setTimeout(callback, options.timeout, options.response);
          return that;
        }
      };
      return that;
    }
    /* Then override api call without touching $.ajax: */
    WriterPanelMessage = function() {
      return mockAjax({
        success: true,
        timeout: 500,
        response: {
          results: {
            result: 'Ok'
          }
        }
      });
    };
    /* Then override api call without touching $.ajax: */
    WriterPanelMessage = function() {
      return mockAjax({
        success: false,
        timeout: 500,
        response: {
          results: {
            result: 'Oh No'
          }
        }
      });
    };
    
    $.ajax = function() {
      return mockAjax({
        success: true,
        response: {
          ok: true
        },
        timeout: 500
      });
    };
    body {
      box-sizing: border-box;
      margin: 0;
      padding: 0;
      font-size: 16px;
      display: grid;
      place-items: center;
      gap: 0.5em;
    }
    
    .message-container,
    .information {
      display: grid;
      grid-template-columns: 1fr;
      grid-template-rows: 2em;
      align-items: center;
      gap: 0.5em;
      justify-content: center;
      border: solid 1px #00FF00;
      background-color: #00FF0040;
      border-radius: 1em;
      padding: 0.5em;
    }
    
    .message-container .testerout {
      border-radius: 2em;
      padding: 0.5em;
    }
    
    .information>* {
      border-bottom: 1px solid;
    }
    
    .information.error,
    .information .error {
      border: solid 1px #FF0000;
      background-color: #FF000010;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <!-- actual <div id="checkDiv" class="message-container" data-postaddress="@Url.Action("RetrieveMessage", "WriterPanelMessage")">-->
    <div id="checkDiv" class="message-container" data-postaddress="WriterPanelMessage\RetrieveMessage">
      <label><input type="checkbox" value="cheers"/>Cheers</label>
      <label><input type="checkbox" value="speech"/>Speeches</label>
      <label><input type="checkbox" value="yells"/>Yells</label>
      <label><input type="checkbox" value="whisper"/>Whisper</label>
      <label><input type="checkbox" value="quiet"/>Silence</label>
      <button class="testerout" type="button">Test Our Code</button>
    </div>
    <div class="information"></div>