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

Time:01-07

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.

int i = 1;    
foreach (var item in Model.messages as List<Message>)
    {    
    <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=""  data-toggle="modal" data-target="#myModal-@i">Open Message</a>
                <input type="hidden" id="msg-id-@i" value="@item.messageId"/>
            </td>
            <td><a type="button" style="color: red"  id="del-@i">Delete</a></td>
        </tr>
i  ;
    }

I want to use ajax calls to do this task:

<script>
    $(document).ready(function(){
        $('#del-@i').on("click", function(){
            var msgId = $('#msg-id-@i').val();
            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("The selected message removed.");
                    }else{
                        alert("Error!");
                    }
                }
            })
        });
    });
</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?

CodePudding user response:

The problem appears to be that the ids listed in the javascript are not going to contain the correct value of i as the generation of the script does not occur in the for loop.

** this answer leverages the jQuery Selector closest

Here are the changes I would suggest;

  1. add an attribute to the row with the ID in it.
    <tr msg-id="@item.messageId">
  1. change your js to determine the row of the button clicked and extract that Id.
    $(document).ready(function(){
        $('.message-link').on("click", function(){
            var msgId = $(this).closest("tr").attr("msg-id");
            var formData = new FormData();
            formData.append("messageId", parseFloat(msgId));

            $.ajax({
                type: "POST",
                url: "Messages/DeleteMessage",
                contentType: false,
                processData: false,
                data: formData,
                success: function(response){
                    if(response.success){
                        alert("The selected message removed.");
                    }else{
                        alert("Error!");
                    }
                }
            })
        });
    });
  •  Tags:  
  • Related