Pass (Send) multiple parameters to JavaScript function on jQuery DataTable row click in ASP.Net

Last Reply 4 months ago By dharmendr

Posted 4 months ago

how to pass multiple parameters to datatable column to check and uncheck checkbox and update data in database.

here i am fetching status from datatabase through web method and update status checked/unchecked using checkbox.

how can i pass id along with status to column.

         $(document).ready(function () {
             $.ajax({
                 success: function (data) {
                     $('#dataTables-example').dataTable({
 
                         columns: [
                             { 'data': 'ID' },
                             { 'data': 'Name' }, 
                               {
                                   'data': 'Status',
                                   'sortable': false,
                                   'searchable': false,
                                   'render': function (Status) {
                                     //   var id = $(this).data('ID');
                                     // var id = row[0];
                                       if (Str_Status=='1') {
                                           return '<label class=switch><input type=checkbox onclick=chk_status(this) data-id=' + data.d[i].ID + ' id=chk_sts_str checked=checked ><span class=slider round></span></label>'
                                       } else {                                            
                                           return '<label class=switch><input type=checkbox onclick=chk_status(this) data-id=' + data.d[i].ID + ' id=chk_sts_str><span class=slider round></span></label>'
                                       }
                                   }
                               },
                         ],
                         bServerSide: true,
                         sAjaxSource: '/WebService.asmx/Getatatable',
                         sServerMethod: 'post'
                     });
                 }, error: function (response) {
                     alert(response.responseText);
                 }
             });
         function chk_status(chk) {
            var id = $(chk).attr("data-id");
             // var id = $(this).parents('tr').find('td');
             //  var row = $(this).parents('tr');
             //  var id = $(row).find('td').eq(0).html();
             var Status = "";
             var isChecked = $(chk).is(":checked");
             if (isChecked) {
                 Status = "1";
             }
             else {
                 Status = "0";
             }
             $.ajax({
                 type: "Post",
                 contentType: "application/json; charset=utf-8",
                 url: "/WebService.asmx/updstrstatus",
                 data: '{Status:' + Status + ',eid:' + id + '}',
                 datatype: "json",
                 success: function (data) {
                     if (data.d > 0) {
                        // alert(" Updated Successfully");
                     }
                 },
                 error: function (data) {
                     alert("Error while Updating data of :" + id);
                 }
             });
         }

 

   [System.Web.Services.WebMethod]
   public void Getdatatable()
   {
       string cs = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
       List<Store> details = new List<Store>();
       using (SqlConnection con = new SqlConnection(cs))
       {
           SqlCommand cmd = new SqlCommand("select ID,Name,Status from Stores", con);
           con.Open();
           SqlDataReader rdr = cmd.ExecuteReader();
           while (rdr.Read())
           { 
               Store user = new Store();               
               user.ID = Convert.ToInt32(rdr["ID"].ToString());
               user.Name = rdr["Name"].ToString();
               user.Status = rdr["Status"].ToString();
               details.Add(user);
           }
       }
       JavaScriptSerializer js = new JavaScriptSerializer();
       Context.Response.Write(js.Serialize(details));
   }
   [WebMethod]
   public int updstrstatus(string Str_Status, int eid)
   {
       int i = 0;
       SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);     
       con.Open();
       SqlCommand cmd = new SqlCommand("update Stores set Status='" + Status + "'where ID='" + eid + "'", con);       
       i = cmd.ExecuteNonQuery();
       con.Close();
        
       return i;
   }

 

Posted 4 months ago Modified on 4 months ago

Hi jovceka,

Check this example. Now please take its reference and correct your code.

Once you get the response in the success function pass that response object to DataTable render function and using the property pass as additional parameter to any function.

HTML

<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 (index, row, data) {
                            var Id = data.Id;
                            var Str_Status = data.Status;
                            if (Str_Status == '1') {
                                return '<label class=switch><input type=checkbox onclick=chk_status(this,' + Str_Status + ',' + Id + ') data-id=' + Id + ' id=chk_sts_str checked=checked ><span class=slider round></span></label>'

                            } else {
                                return '<label class=switch><input type=checkbox onclick=chk_status(this,' + Str_Status + ',' + Id + ') data-id=' + Id + ' id=chk_sts_str><span class=slider round></span></label>'
                            }
                        }
                    }]
                });
            }, error: function (response) {
                alert(response.responseText);
            }
        });
    });
    function chk_status(chk, status, id) {
        var Status = "";
        var isChecked = $(chk).is(":checked");
        if (isChecked) {
            Status = "1";
        }
        else {
            Status = "0";
        }
        alert("Status : " + Status + "\nId : " + id + "\nPrevious Status : " + status);
    }
</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>
                </tr>
            </thead>
        </table>
    </div>
</div>

WebService

C#

using System;
using System.Web.Script.Serialization;
using System.Web.Services;

/// <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; }
        public int Status { get; set; }
    }

    [WebMethod]
    public void GetFiles()
    {
        List<File> files = new List<File>();
        files.Add(new File { Id = 1, Name = "Chrysanthemum.jpg", Status = 1 });
        files.Add(new File { Id = 2, Name = "Desert.jpg", Status = 0 });
        files.Add(new File { Id = 6, Name = "Koala.jpg", Status = 1 });

        JavaScriptSerializer js = new JavaScriptSerializer();
        Context.Response.Write(js.Serialize(files));
    }
}

VB.Net

Imports System.Web
Imports System.Web.Services
Imports System.Web.Script.Serialization
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
        Public Property Status As Integer
    End Class

    <WebMethod()> _
    Public Sub GetFiles()
        Dim files As List(Of File) = New List(Of File)()
        files.Add(New File With {.Id = 1, .Name = "Chrysanthemum.jpg", .Status = 1})
        files.Add(New File With {.Id = 2, .Name = "Desert.jpg", .Status = 0})
        files.Add(New File With {.Id = 6, .Name = "Koala.jpg", .Status = 1})
        Dim js As JavaScriptSerializer = New JavaScriptSerializer()
        Context.Response.Write(js.Serialize(files))
    End Sub
End Class

Screenshot