Link to home
Start Free TrialLog in
Avatar of Michael Sterling
Michael SterlingFlag for United States of America

asked on

How do I pass a value from my jQuery DataTable row?

How do I pass a value from my jQuery DataTable row, to my C# WebMethod? In the following code segment, when you hover over the checkmark / link image, there is a call made to a C# WebMethod, that returns a value which is used by an alert call to display some information (now, simply the DateTime presently for testing). I'd like to pass a specific value, from the current row, to use in that WebMethod to be processed and return a value to be used in that alert call. How do I do this?

<%@ Page Title="" Language="C#" MasterPageFile="MasterPageStock.master" AutoEventWireup="true" CodeFile="SignInGrid.aspx.cs" Inherits="SignInGrid" %>

<asp:Content ID="Content0" ContentPlaceHolderID="head" runat="Server">
    <style type="text/css">
        .divFade {
            display: none;
            position: absolute;
            overflow: hidden;
            z-index: 10000;
        }

        td.details-control {
            background: url('Images/bullet_add.png') no-repeat center center;
            cursor: pointer;
        }

        tr.shown td.details-control {
            background: url('Images/red_minus.png') no-repeat center center;
        }

        .navbar-right {
            display: block;
        }

        .lnkBtnLogOut, .pageTitle {
            display: inline;
        }

        .rwBtn {
            margin: 30px 0 0 0;
        }
    </style>

    <script type="text/javascript">
        //MYSQL DB VERSION
        $(document).ready(function () {
            $(".divFadeInOut").fadeToggle(4000);
            $.ajax({
                "url": "SignInGrid.aspx/getData",
                "type": "POST",
                "contentType": "application/json; charset=utf-8",
                "dataType": "json",
                success: function (json) {
                    var table = $('#example').DataTable({
                        "columns": [
                            {
                                "className": "dt-body-center",
                                "targets": 0,
                                "data": "StudentID",
                                "render": function (data, type, full, meta, oData) {
                                    return '<a href="StudentAthleteInfo.aspx?StudentID=' + data + '">' + data + '</a>';
                                }
                            },
                            {
                                "className": "dt-body-center",
                                "data": "StudentName"
                            },
                            {
                                "className": "dt-body-center",
                                "data": "TimeIn"
                            },
                            {
                                "className": "dt-body-center",
                                "data": "TimeSignedIn"
                            },
                            {
                                "className": "dt-body-center",
                                "targets": 0,
                                "data": "StudentID2",
                                "render": function (data, type, full, meta, oData) {
                                    return '<a href="StudentAthleteInfo.aspx?StudentID=' + data + '&showweektotal=y" class="glyphicon glyphicon-ok text-center hovr-link" style="color: green;"></a>';
                                }
                            },
                            {
                                "className": "dt-body-center",
                                "targets": 0,
                                "data": "StudentID3",
                                "render": function (data, type, full, meta, oData) {
                                    return '<a href="StudentAthleteInfo.aspx?StudentID=' + data + '&signout=y" class="glyphicon glyphicon-time text-center" style="color: red;"></a>';
                                }
                            },
                        ],
                        "aaData": $.parseJSON(json.d)
                    });
                    //HERE IS WHERE THE MOUSEOVER CALLS MY WEB METHOD. HOW DO I PASS A SPECIFIC VALUE FROM MY ROW TO THIS???
                    $('body').on('mouseover', '.hovr-link', function (e) {
                        $.ajax({
                            type: "POST",
                            url: "SignInGrid.aspx/GetRecords",
                            data: "{}",
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            success: function (result) {
                                // Do something with records returned here
                                // Use result.d to get to JSON data
                                alert(result.d);
                            }
                        });
                    });

                    $('body').on('mouseout', '.hovr-link', function (e) {
                        $('div#pop-up').hide();
                    });
                }
            });

            var lblVal = $(".userIDLabel").html();
            var lblVal1 = $(".dealerTypeLabel").html();

            if (lblVal.indexOf("ADMIN") >= 0) {
                $(".adminLinks").css("display", "block");
                $("#liViewVendorSubmissions").css("display", "block");
                $("#liVendorList").css("display", "none");
                $("#topdropdown").css("display", "none");

                $("#liSearchInvintoryMenuItem").css("display", "none");
                $("#liRequstBoardMenuItem").css("display", "none");
                $("#liProfileMenuItem").css("display", "none");
                $("#liContactUsMenuItem").css("display", "none");
            }
            else {
                $(".adminLinks").css("display", "none");
            }
        });

        $(document).on('click', '#btnWeekTotal', null, function () {
            var url = this.getAttribute("data-url");
            alert(url);
            alert(window.location);
            window.location = url;

        });

        $(function () {
            var moveLeft = 0;
            var moveDown = 0;

            $('a#lnkweektotal').hover(function (e) {
                $('div#pop-up').show();
            }, function () {
                $('div#pop-up').hide();
            });

            $('a#lnkweektotal').mousemove(function (e) {
                $("div#pop-up").css('top', e.pageY + moveDown).css('left', e.pageX + moveLeft);
            });
        });
    </script>
</asp:Content>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="Server">
    <div class="row myRow">
        <div class="col-lg-12 text-page-title-center" style="background: #000; height: 33px;">
            <div id="divPageTitle" class="center-page-title center" runat="server">
                <asp:Label class="pageTitle" runat="server" ID="pageTitle" Text="SIGNED IN LIST"></asp:Label>
            </div>
        </div>
    </div>
    <table id="example" class="display responsive nowrap" data-page-length="10" width="100%" cellspacing="0">
        <thead>
            <tr>
                <th class="dt-head-center dt-body-center" data-orderable="true">StudentID</th>
                <th class="dt-head-center" data-orderable="true">StudentName</th>
                <th class="dt-head-center" data-orderable="true">TimeIn</th>
                <th class="dt-head-center" data-orderble="true">TimeSignedIn</th>
                <th class="dt-head-center">Week Total</th>
                <th class="dt-head-center">Sign Out</th>
                <%--<th>Delete</th>--%>
            </tr>
        </thead>
    </table>
    <p>
        <a href="#" id="lnkweektotal">Show pop up</a>
    </p>
    <div id="pop-up" style="display: none;">
        <h3>Pop-up div Successfully Displayed</h3>
    </div>
        <div id="divFader" runat="server" class="col-xs12 divFade">
        <h4 id="H2" style="color: green;">
            <asp:Label runat="server" ID="lblUpdateConfMsg" Font-Bold="true" Font-Size="X-Large"></asp:Label></h4>
    </div>
</asp:Content>

Open in new window


C# WebMethod
    [WebMethod]
    public static string GetRecords()
    {
        return DateTime.Now.ToString();
    }

Open in new window

Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Question
Line 83
"aaData": $.parseJSON(json.d)

Open in new window

You are requesting a JSON return in your AJAX call and then you do a parseJSON on the result - does not make sense.

Back to your query
Change your mouseover to this

$('body').on('mouseover', '.hovr-link', function (e) {
  // Get the <tr> parent so you can access the row data
  var parent = $(this).closest('tr');

  // Get access to the datatable
  var table = $('#example').DataTable();

  // Get the row data
  var data = table.row(parent).data();

// Dump to console to debug - REMOVE FOR PRODUCTION CODE
console.log(data);
  $.ajax({
    type: "POST",
    url: "SignInGrid.aspx/GetRecords",
    data: data,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (result) {
      // Do something with records returned here
      // Use result.d to get to JSON data
      alert(result.d);
    }
  });
});

Open in new window

In your event handler get the parent <tr>. Using the parent you can now use the dataTables .data method to access all the data in the row - returned as a JavaScript object so you can pick and choose which of the data items you want to use (or all of them as in the example above)
Avatar of Michael Sterling

ASKER

@Julian Hansen: I'm new to this so I followed an example and when it worked I didn't know enough about it to know that part didn't make sense. What should that line be, to achieve the same results?

Also I put your code in place and it worked, up to the point of, in my C# WebMethod, what parameter/object should I now be taking in / passing to it?

I tried this:
    [WebMethod]
    public static string GetRecords(string StudentID)
    {
        return StudentID;
    }

Open in new window


but got this error:
{"Message":"Invalid JSON primitive: StudentID.","StackTrace":"   at System.Web.Script.Serialization.JavaScriptObjectDeserializer
.DeserializePrimitiveObject()\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.DeserializeInternal
(Int32 depth)\r\n   at System.Web.Script.Serialization.JavaScriptObjectDeserializer.BasicDeserialize
(String input, Int32 depthLimit, JavaScriptSerializer serializer)\r\n   at System.Web.Script.Serialization
.JavaScriptSerializer.Deserialize(JavaScriptSerializer serializer, String input, Type type, Int32 depthLimit
)\r\n   at System.Web.Script.Serialization.JavaScriptSerializer.Deserialize[T](String input)\r\n   at
 System.Web.Script.Services.RestHandler.GetRawParamsFromPostRequest(HttpContext context, JavaScriptSerializer
 serializer)\r\n   at System.Web.Script.Services.RestHandler.GetRawParams(WebServiceMethodData methodData
, HttpContext context)\r\n   at System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext
 context, WebServiceMethodData methodData)","ExceptionType":"System.ArgumentException"}

Open in new window

@Julian Hansen: Never mind, I figured out how to get my data! But thank you for your help! I'd still like to gain some insight as to what you mentioned above about it not making sense that I'm: "requesting a JSON object in my AJAX call, but then I'm doing a parseJSON on the result -" conceptually I not needing to do a thing, but the "why" of it is what I'm missing. Again, I'm new to this jQuery DataTable / AJAX / JSON thing so I'm sure I will make some mistakes, but any knowledge I can pick up along the way on my journey, I'd appreciate. I'll leave this open for a while to discuss further but you'll still get full credit for this. Thanks again.
ASKER CERTIFIED SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thank you for your input/insight on this.
You are welcome.
Thank you.