in

How to use ajax call for deleting database rows and updating the table in the page?


I have a table in my page that its content is filled based on database entries. I use foreach loop to iterate through the database rows and fill the table. The last column has delete button which is shown in each row. This button deletes that specific row from the table.

<tr>
    <td>@i</td>
                                                        
    <td>@dConverter.DateConverter(@item.messageDate.ToShortDateString())</td>
                                                        
    <td>@dConverter.GetTime(@item.messageDate.ToString())</td>
    <td>@Model.usersList.First(x => x.Id == item.senderId).department</td>
    <td>
        <a href="" class="message-link" data-toggle="modal" data-target="#myModal-@i">مشاهده</a>
        <input type="hidden" id="msg-id-@i" value="@item.messageId"/>
    </td>
    <td><a type="button" style="color: red" class="message-link" id="del-@i">حذف</a></td>
</tr>

I want to use ajax calls to do this task:

<script>
    $(document).ready(function(){
        $('#del-@i').on("click", function(){
            var msgId = $('#msg-id-@i');
            var formData = new FormData();
            formData.append("messageId", msgId);

            $.ajax({
                type: "POST",
                url: "Messages/DeleteMessage",
                contentType: false,
                processData: false,
                data: formData,
                success: function(response){
                    if(response.success){
                        alert("پیام مورد نظر حذف شد.");
                    }else{
                        alert("خطا در عملیات!");
                    }
                }
            })
        });
    });
</script>

The code for the action that do the deleting task is:

[HttpPost]
        public JsonResult DeleteMessage(int messageId) 
        {
            bool response = _messageRepository.DeleteMessageById(messageId);
            if(response == true)
            {
                return Json(new { success=true});
            }
            else
            {
                return Json(new { success=false });
            }
        }

The problem is that when I press the button, nothing happens. I tried to debug the action in controller and saw that this action is not called when I press the button. There may be a matching error in ids between javascript and the razor codes. How can I fix it?



Source: https://stackoverflow.com/questions/70610620/how-to-use-ajax-call-for-deleting-database-rows-and-updating-the-table-in-the-pa

COAI Urges DoT to Provide Continuous Support for Telecom Services During Pandemic

BSNL Completely Revamps Benefits of Rs 999 Broadband Plan