• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 274
  • Last Modified:

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

0
Michael Sterling
Asked:
Michael Sterling
  • 4
  • 3
1 Solution
 
Julian HansenCommented:
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)
1
 
Michael SterlingWeb Applications DeveloperAuthor Commented:
@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

0
 
Michael SterlingWeb Applications DeveloperAuthor Commented:
@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.
0
Veeam Disaster Recovery in Microsoft Azure

Veeam PN for Microsoft Azure is a FREE solution designed to simplify and automate the setup of a DR site in Microsoft Azure using lightweight software-defined networking. It reduces the complexity of VPN deployments and is designed for businesses of ALL sizes.

 
Julian HansenCommented:
Apologies for the late response - I must have missed the notifications of your above two posts.

Your first question: What should that line be, to achieve the same results?

When you specify dataType: "json" in your AJAX call, JQuery will convert the return to JSON for you.

The only time you want to call parseJSON is when the returned data is in string format - i.e. has not been converted to a JSON object. As to what that line should be - I cannot say without knowing
a) What the return from the server is - if you do a
console.log(json)
in your success function and then post the results of the Response from your console (Press F12, select console and then expand the POST entry - click the Response tab and copy the content from there)
b) What the intended use case is of the aaData member

As to the why (your second post) here is a synopsis.

When you request data from the server you do so by sending a Request header - which includes any parameters you want to send as well as the method you are sending them (POST / GET). You can also send an HTTP header that specifies what format you expect the data to be returned as. When you add the
dataType: "JSON"
Member to your AJAX request you tell JQuery that the data you are getting back is in JSON format. JQuery then knows that it must do a parseJSON on the return before calling your success function.

If you left out the dataType property in your call and your server script did a JSON return then you would have to do parseJSON on the results - so it is an either or - in the first case JQuery does the work for you automatically - in the second you have to manually do the conversion.

I put together a sample for you to explain what is going on. You can access it here
If you open the console (F12) and click the Go button on the sample you should see some output in the console. If the checkbox is not checked you will see a JSON string (the return from the AJAX WITHOUT dataType JSON) followed by an Object - the result of calling $.parseJSON on the return.
If the checkbox is checked (dataType: JSON is set) then the first output will be an object - the native success return (JQuery auto parses the string) - and an error on the second output because we are calling $.parseJSON on an object not a string.

Source code for the key parts of the sample are as follows
HTML
  Set dataType:JSON <input type="checkbox" id="sendjson" /><br/>
  <button class="go btn btn-primary">Go</button><br/>

Open in new window

JQuery
<script>
$(function() {
  $('.go').click(function(e) {
    e.preventDefault();
    var params = {
      url: "sendsomejson.php",
      type: "post",
    }
    if ($('#sendjson:checked').length > 0) {
      params.dataType = "json";
    }
    $.ajax(params)
      .then(function(response) {
        console.log('This is what JQuery returns ... if checkbox is checked you see an object otherwise you see a string');
        console.log(response);
        console.log('Result of $.parseJSON - if checkbox is checked this should be an error');
        var x = $.parseJSON(response);
        console.log(x);
    });
  });
});
</script>

Open in new window

1
 
Michael SterlingWeb Applications DeveloperAuthor Commented:
Thank you for your input/insight on this.
0
 
Julian HansenCommented:
You are welcome.
0
 
Michael SterlingWeb Applications DeveloperAuthor Commented:
Thank you.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

  • 4
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now