Get (Retrieve) jQuery DataTable row id on CheckBox checked (selected) using jQuery

Last Reply 5 months ago By pandeyism

Posted 5 months ago

In the below datatable(not working)...how can i pass ID to status column

columns: [
    { 'data': 'ID' },
    { 'data': 'Name' },
    {
        'data': 'Status',
        'sortable': false,
        'searchable': false,
        'render': function (Status){
            //  var ID = $(this).data('ID');
            if (Status=='1') {
                 return '<input type=checkbox onclick=chkstatus(this)  data-id=' + ID + ' id=chk_sts_str checked=checked >'
            } else {
                return '<input type=checkbox onclick=chk_status(this) data-id=' + ID + '  id=chk_sts_str>'
            }
        }
    },

 

Posted 5 months ago

Hi jovceka,

Refer below sample.

Database

For this example i have used table named tblFiles whose schema is defined as follows.

For save record in databse refer below article.

Save and Retrieve images from database in ASP.Net

HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
    <script type="text/javascript" src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
    <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.7/css/jquery.dataTables.min.css" />
    <script type="text/javascript" src="https://cdn.datatables.net/1.10.7/js/jquery.dataTables.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $.ajax({
                url: '<%= Page.ResolveUrl("~/WebService.asmx/GetFiles")%>',
                method: 'post',
                dataType: 'json',
                success: function (data) {
                    $('#datatable').dataTable({
                        paging: true,
                        sort: true,
                        pageLength: 3,
                        searching: true,
                        data: data,
                        columns: [
                        { 'data': 'Id' },
                        { 'data': 'Name' },
                        {
                            'data': 'Id',
                            'sortable': false,
                            'searchable': false,
                            'render': function (Id) {
                                if (!data) {
                                    return '<input type="checkbox" onclick="chk_status(this)" data-id="' + Id + '"  id="chk_sts_str" />'
                                }
                                else {
                                    return '<input type="checkbox" onclick="chk_status(this)" data-id="' + Id + '"  id="chk_sts_str" />'
                                }
                            }
                        },
                        {
                            "data": null,
                            "defaultContent": '<input type="button" id="btnEdit" class="btn btn-primary" value="Edit" />'
                        },
                        {
                            "data": null,
                            "defaultContent": '<input type="button" id="btnDelete" class="btn btn-danger" value="Delete" />'
                        }
                        ]
                    });
                }, error: function (response) {
                    alert(response.responseText);
                }
            });
        });
        function chk_status(ele) {
            alert("Selected data id is : " + $(ele).data('id'));
        }
    </script>
    <div>
        <div style="width: 100%; border: 1px solid black; padding: 3px">
            <table id="datatable">
                <thead>
                    <tr>
                        <th>Id</th>
                        <th>Name</th>
                        <th>Select</th>
                        <th>Edit</th>
                        <th>Delete</th>
                    </tr>
                </thead>
            </table>
        </div>
    </div>
    </form>
</body>
</html>

Code

C#

WebService.cs

using System;
using System.Collections.Generic;
using System.Web.Services;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Web.Script.Serialization;

/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
    public class File
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

    [WebMethod]
    public void GetFiles()
    {
        string cs = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        List<File> files = new List<File>();
        using (SqlConnection con = new SqlConnection(cs))
        {
            SqlCommand cmd = new SqlCommand("SELECT id,Name FROM tblFiles WHERE ContentType = 'image/jpeg'", con);
            cmd.CommandType = CommandType.Text;
            con.Open();
            SqlDataReader rdr = cmd.ExecuteReader();
            while (rdr.Read())
            {
                File file = new File();
                file.Id = Convert.ToInt32(rdr["id"]);
                file.Name = rdr["Name"].ToString();
                files.Add(file);
            }
            con.Close();
        }
        JavaScriptSerializer js = new JavaScriptSerializer();
        Context.Response.Write(js.Serialize(files));
    }

    [WebMethod]
    public int DeleteFile(int id)
    {
        string cs = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        List<File> files = new List<File>();
        using (SqlConnection con = new SqlConnection(cs))
        {
            SqlCommand cmd = new SqlCommand("DELETE FROM tblFiles WHERE id = @Id", con);
            cmd.CommandType = CommandType.Text;
            cmd.Parameters.AddWithValue("@Id", id);
            con.Open();
            int i = Convert.ToInt32(cmd.ExecuteScalar());
            con.Close();
            return i;
        }
    }
}

WebService.cs

Imports System.Web
Imports System.Collections.Generic
Imports System.Configuration
Imports System.Data
Imports System.Data.SqlClient
Imports System.Web.Script.Serialization
Imports System.Web.Services
Imports System.Web.Services.Protocols
 
' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class WebService
    Inherits System.Web.Services.WebService
 
    Public Class File
        Public Property Id As Integer
        Public Property Name As String
    End Class
 
    <WebMethod()> _
    Public Sub GetFiles()
        Dim cs As String = ConfigurationManager.ConnectionStrings("constr").ConnectionString
        Dim files As List(Of File) = New List(Of File)()
        Using con As SqlConnection = New SqlConnection(cs)
            Dim cmd As SqlCommand = New SqlCommand("SELECT id,Name FROM tblFiles WHERE ContentType = 'image/jpeg'", con)
            cmd.CommandType = CommandType.Text
            con.Open()
            Dim rdr As SqlDataReader = cmd.ExecuteReader()
            While rdr.Read()
                Dim file As File = New File()
                file.Id = Convert.ToInt32(rdr("id"))
                file.Name = rdr("Name").ToString()
                files.Add(file)
            End While
        End Using
        Dim js As JavaScriptSerializer = New JavaScriptSerializer()
        Context.Response.Write(js.Serialize(files))
    End Sub
End Class

Screenshot