Master the Art of Modifying a Row in Datatable with .NET Core

I am having trouble updating a row in my datatable using .net core. The datatable display the data correctly and the new/delete buttons are working. However, when I try to edit a row, it is not functioning properly.

Below is my index.cshtml code. Thank you.

"ajax": {
  "url": "../LoadIntervaloTrabajo",
  "type": "POST",
  "data": { "codigo": @Model.codigo},
  "datatype": "json"
  },
  "columns": [
     { "data": "horario", "autowidth": true },
     { "data": "codigo", "autowidth": true },
     { "data": "descripcion", "autowidth": true },
     { "data": "horainicio", "autowidth": true },
     { "data": "duracion", "autowidth": true },
     { "data": "cortentrada", "autowidth": true },
     { "data": "cortintermedia", "autowidth": true },
     { "data": "cortsalida", "autowidth": true },
     { "render": function (data, type, row) { 
                     return "<a href='#' class='btn btn-info' onclick=EditData('" + row.codigo + "'); >Editar</a>"; 
                                                   }
                     },
                 function EditData(codigo) {
                       var table = $("#customerDatatable").DataTable();
                       var r = table.rows(".selected").nodes()[0];
                       if ($(table.buttons(".editButton")[0].node).find("span").text() == "Cancel") {
                           $(r).children("td").each(function (i, it) {
                                if (i > 0) {
                                    var od = table.cells(it).data()[0];
                                    $(it).html(od);
                                }
                           });                                              
                           setButtons('cancel');
                       } else {
                           $(r).children("td").each(function (i, it) {
                                if (i > 0) {
                                    var h = $("<input type='text'>");
                                    h.val(it.innerText);
                                    $(it).html(h);
                                }
                           });
                           setButtons('edit');
                       }

Answer №1

I am facing an issue while trying to update a row in my datatable using .NET Core.

For the implementation of the row updating functionality, you can refer to the following unique code snippet.

Create two buttons for updating a specific row within the last column

"columns": [
    {
        "data": "horario", "autowidth": true
    },
    { "data": "codigo", "autowidth": true },
    { "data": "descripcion", "autowidth": true },
    { "data": "horainicio", "autowidth": true },
    { "data": "duracion", "autowidth": true },
    { "data": "cortentrada", "autowidth": true },
    { "data": "cortintermedia", "autowidth": true },
    { "data": "cortsalida", "autowidth": true },
    {
        "render": function (data, type, row) { return "<a href='#' class='btn btn-info' onclick = EditRow(this); >Edit</a><a href='#' class='btn btn-info btn-hidden' onclick = UpdateRow(this); >Update</a>"; }
    }
]

JavaScript function

function EditRow(btnedit) {
    // Find the current row
    var $row = $(btnedit).parent().parent();
    var $tds = $row.find("td").not(':nth-child(2)').not(':last');

    $.each($tds, function (i, el) {
        var txt = $(this).text();
        $(this).html("").append("<input type='text' value=\"" + txt + "\">");
    });
    $(btnedit).siblings("a").removeClass("btn-hidden");
    $(btnedit).addClass("btn-hidden");
}

function UpdateRow(btnupdate) {
    var $row = $(btnupdate).parent().parent();

    var horario = $row.find("td:nth-child(1)").find("input").val();
    var codigo = $row.find("td:nth-child(2)").text();
    var descripcion = $row.find("td:nth-child(3)").find("input").val();
    var horainicio = $row.find("td:nth-child(4)").find("input").val();
    var duracion = $row.find("td:nth-child(5)").find("input").val();
    var cortentrada = $row.find("td:nth-child(6)").find("input").val();
    var cortintermedia = $row.find("td:nth-child(7)").find("input").val();
    var cortsalida = $row.find("td:nth-child(8)").find("input").val();


    var data_for_update = { "horario": horario, "codigo": codigo, "descripcion": descripcion, "horainicio": horainicio, "duracion": duracion, "cortentrada": cortentrada, "cortintermedia": cortintermedia, "cortsalida": cortsalida };

    //console.log(data_for_update);

    // Make a request to update the data
    $.ajax({
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        url: "/{controller_name_here}/Update",
        data: JSON.stringify(data_for_update),
        success: function (json) {
            console.log(json);
            var $tds = $row.find("td").not(':nth-child(2)').not(':last');

            $.each($tds, function (i, el) {
                var txt = $(this).find("input").val()
                $(this).html(txt);
            });
            $(btnupdate).siblings("a").removeClass("btn-hidden");
            $(btnupdate).addClass("btn-hidden");
        },
        //...
    });


            
}

CSS style

.btn-hidden{
    display:none;
}

Test Result:

https://i.stack.imgur.com/zfoZD.gif

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be causing the browser to become unresponsive when making several AJAX requests to the same ASP.NET MVC action at once?

The other day, I posed this query: Why is $.getJSON() causing the browser to block? I initiated six jQuery async ajax requests simultaneously on the same controller action. Each request takes around 10 seconds to complete. Upon tracking and logging re ...

How to Automatically Close an Ajax Modal Popup After Executing Code in ItemCommand in ASP.Net

I am currently facing an issue with closing a ModalPopup after a code sequence is executed. The situation at hand involves coding a filebrowser for the company and everything seems to be working fine except for the downloading of files. I have implemented ...

The HTML element failed to be inserted

Currently, I am involved in a project based on .NET Core for my organization. This project entails loading work orders from our SQL database using Entity Framework and then filtering them to display as markers on a map via the Google Maps API for our insta ...

retrieve content within an iframe via ajax

I currently have an iframe set up on the server side like this: <iframe frameborder="0" runat="server" style="width: 100%; height: 700px; background-color: #bacad3;" id="I1" name="I1" src="Page.aspx"></iframe> and I update the content dynamic ...

"Create a notification pop-up in CSS that appears when a link is clicked, similar to

I am looking to create a model page that functions similarly to the inbox popup on Stack Overflow. When we click on the inbox icon, a small box appears with a tiny loader indicating messages or comments. The box then expands depending on the content inside ...

Convert JSON data to a PHP variable

When I try to pass some JSON data to a PHP file, the variables in the PHP code end up empty. I suspect it's due to a small syntax error, but I can't pinpoint the exact cause. Any assistance would be highly appreciated. JAVASCRIPT if(score >= ...

Three pie or doughnut charts instead of one are utilized within Chart.js

Can multiple charts be nested inside one another? To see an example of a single chart and what I would like - where the first one is placed inside the second one and so on - please refer to this js fiddle. var data = [ { label: "title 1", value: ...

Mustache.js integrated with backbone.js failing to render content in the desired div location

Currently, I am utilizing backbone.js alongside Mustache as my template engine. Within one of my backbone views, there are various functions in play, with one specifically responsible for rendering a drop-down list populated with items retrieved from a dat ...

Tips for making an AJAX request using jQuery

I have a new project that involves collecting user data and displaying it on the same page. I was able to successfully implement an Ajax call using JavaScript, but now I want to transition to using jQuery. Below is my JavaScript code: var output1 = docum ...

Encountering a problematic JQuery Ajax request to a RESTful API

I am currently in the process of trying to authenticate against demo webservices that were developed by one of my colleagues. While Cross-origin resource sharing is allowed and functions perfectly when I attempt to call from the Advanced Rest Client plugin ...

Issue with jQuery DataTables column.width setting failing to meet expectations

Currently, I am utilizing datatables for my project. According to the datatables documentation found here, it suggests using the columns.width option to manage column width. However, when I implement columns.width and render the table, it seems to disreg ...

Comparing $.fn.fancybox and $.fancybox: What sets them apart?

I'd like to understand the distinction between the two items shown above. In what ways do they differ from each other? ...

Utilizing jQuery to target elements that are dynamically generated upon successful AJAX response

When handling dynamically created elements on ajax success, I encountered an issue. I have multiple checkboxes within a table and when the table content is replaced on ajax success, I am unable to select any new checkbox. While it is possible to trigger cl ...

Implementing a horizontal scrollbar for an AJAX datatable

Is there a way to incorporate a horizontal scrollbar into an Ajax Datatable? I attempted to use "ScrollX" :true, however, this method did not prove successful. $(document).ready(function () { $('#myDataTable1').DataTable({ "aj ...

How can you use ajax to update the content of a single div in Yii?

I encountered a little issue when attempting to refresh the content of my div using Ajax, as it ends up replacing the entire page within that div. This is causing some trouble for me. Here is a snapshot of the problem: Problem Screenshot You can view my ...

changing the value of a text input based on the selected option in a dropdown using ajax

I attempted to update the text input value with data from the database after selecting an option from the dropdown list. However, I encountered an issue where the data is not populating the text input field. <?php //Including the database configuration ...

React's componentDidMount fails to trigger for jQuery AJAX request

Here is my code snippet: import React from 'react'; import {render} from 'react-dom'; class App extends React.Component { constructor(props) { super(props); this.state = { data: '' }; ...

Tips for verifying the password of a protected post using ajax?

I have set a password for a protected post. Now, I want to verify the entered password using ajax. Here is the HTML code: <form class="protected-post-form" action=".../wp-pass.php" method="post> <input name="post_password" id="pwbox-4470" t ...

Automatically sign in and connect to the Oracle ADF application through Oracle Apex for seamless access

Currently utilizing Oracle Apex 5.1, I have a requirement in my application to access an Oracle ADF application from Oracle Apex. To achieve this, I decided to embed the ADF application within an Iframe in Apex. The issue arises when users are required to ...

transferring data from a web page to a php script seamlessly without navigating away

I've already spent a significant amount of time searching on Stack Overflow and Google, but I haven't found a solution that works for me. My issue is that I have an HTML form and I need to send the data to PHP without redirecting or leaving the ...