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

asked on

How do I get the right piece of data (cell) to my C# WebMethod, from my jQuery DataTable through my $ajax call?

I'm so very close to getting this to completely work. I've built a jQuery DataTable and filled it dynamically with data. I'm trying to make it so that when the user hover's over the green check mark, in a row, the correct "Student ID" for that row (see the attached image) gets sent to my C# WebMethod. As it stands, when ever I roll over a green check mark, in any row, I always get the same value (the same Student ID, the value in the first row: 1902471) passed to my C# WebMethod. I need to do some processing of this value to return a string, but it needs to be the specific value, unique from each row. How do I get the correct, unique Student ID for each row? I think I know where I'm going wrong but don't know how to fix it. See my note: "<---I THINK HERE IS WHERE I'M GOING WRONG?" in my code below.

my HTML & jQuery/javascript/AJAX
<%@ 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 id="std-id" 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)
                    });

                    //ON HOVER, THIS WILL GRAB THE ID VALUE TO BE PROCESSED IN THE 'GetRecords' WEBMETHOD
                    $('body').on('mouseover', '.hovr-link', function (e) {                        
                        var strfy = '{ID:' + $('a#std-id').html() + '}'; <---I THINK HERE IS WHERE I'M GOING WRONG?
                        $.ajax({
                            type: "POST",
                            url: "SignInGrid.aspx/GetRecords", <---THIS IS MY C# WEBMETHOD THAT GETS PASSED THE VALUE
                            data: strfy,
                            contentType: "application/json; charset=utf-8",
                            dataType: 'json',
                            success: function (result) {
                                alert(result.d);
                            }
                        });
                    });
                }
            });

            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


my C# WebMethod
    [WebMethod]
    public static string GetRecords(string ID)
    {
        return ID;
    }

Open in new window


User generated image
Avatar of David Johnson, CD
David Johnson, CD
Flag of Canada image

I don't suggest mixing aspx and jquery as you are mixing client side and server side technologies
Blind guess, replace couple of code and test with that!

return '<a href="StudentAthleteInfo.aspx?StudentID=' + data + '&showweektotal=y" class="glyphicon glyphicon-ok text-center" 
	onmousehover="someFunction('+data+')" style="color: green;"></a>';

Open in new window

Replace above code as below
return '<a id="'+data+'" href="StudentAthleteInfo.aspx?StudentID=' + data + '&showweektotal=y" class="glyphicon glyphicon-ok text-center hovr-link" 
	style="color: green;"></a>';

Open in new window

and in mouse over event,
var strfy = '{ID:' + $('a#std-id').html() + '}';

Open in new window

replace above code as below
var strfy = '{ID:"' + $(this).attr('id') + '"}';

Open in new window

Avatar of Michael Sterling

ASKER

@Prakash Samariya: My original:

"return '<a href="StudentAthleteInfo.aspx?StudentID=' + data + '&showweektotal=y" class="glyphicon glyphicon-ok text-center" style="color: green;"></a>';"

doesn't include a: onmousehover="someFunction('+data+')" property in it, so I'm not sure I understand that part. But I took your other suggestions and put them in place and I'm still getting the same value, the first Student ID value, no matter which green check mark that I hover over.
@David - is there something in particular you're referring to as "mixed" ?  Because I'm not seeing it.  The structure looks correct to me.  I don't see the mixing you're referring to.  It's perfectly valid to have JavaScript in an aspx page, just as it's valid to have JavaScript in a PHP page.  What becomes a problem is when someone tries to access JavaScript from PHP, or access JavaScript from C#, etc.  I don't see that here.  Or maybe I just haven't had enough coffee and I'm missing it?
Line 51 is a problem.  It's invalid HTML to have more than one element on a page with the same ID.  You should use a class instead of id attribute.

To get the student id of the cell you're hovering over:

Add a data attribute that holds the value of the student id to your link on line 71:

return '<a data-studentId="' + data + '" href="StudentAthleteInfo.aspx?StudentID=' + data + '&showweektotal=y" class="glyphicon glyphicon-ok text-center hovr-link" style="color: green;"></a>';

Open in new window


You can then access it like so:

$('body').on('mouseover', '.hovr-link', function (e) { 
	var studentId = $(this).attr('data-studentId');
	//..and so on

Open in new window


Here is a Fiddle Demo.

Given the following HTML:

<span id="result" style="color: red;"></span>
<div id="dialog" title="Stuff">
  <p></p>
</div>
<table>
  <thead>
    <tr>
      <th>Rendering engine</th>
      <th>Browser</th>
      <th>Platform(s)</th>
      <th>Engine version</th>
      <th>CSS grade</th>
      <th>Link</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Trident</td>
      <td>Internet Explorer 4.0</td>
      <td>Win 95+</td>
      <td> 4</td>
      <td>X</td>
      <td><a class="hover" data-studentId="47" href="www.google.com">Student 47</a></td>
    </tr>
    <tr>
      <td>Trident</td>
      <td>Internet Explorer 5.0</td>
      <td>Win 95+</td>
      <td>5</td>
      <td>C</td>
      <td><a class="hover" data-studentId="55" href="www.google.com">Student 55</a></td>
    </tr>
    <tr>
      <td>Trident</td>
      <td>Internet Explorer 5.5</td>
      <td>Win 95+</td>
      <td>5.5</td>
      <td>A</td>
      <td><a class="hover" data-studentId="99" href="www.google.com">Student 99</a></td>
    </tr>
  </tbody>
</table>

Open in new window


JQuery:
$('table').DataTable();

$('.hover').on('mouseover', function() {
console.log($(this).attr('data-studentId'));
  $('#result').text('You hovered over student id ' + $(this).attr('data-studentId'));
});

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Prakash Samariya
Prakash Samariya
Flag of India 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
Student ID" for that row (see the attached image) gets sent to my C# WebMethod.
he is mixing jquery and a c# web method
I have solved this, and I will post my solution at a later time as I am on my cell phone presently and do not have access to my solution.
@Prakash Samariya: So this is the other way to solve this:

$('body').on('mouseover', '.hovr-link', function (e) {
                        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: JSON.stringify(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


but your solution also works. and for that reason, I'll be awarding you the points.

@David Johnson, CD, MVP: Just curious, from a novice's point of view, why would you not want to mix client side and server side technologies? What is the danger / are the dangers that I need to be aware of? Knowledge is power!
@David Johnson - there is absolutely no mixing going on when one sends data from jQuery to a c# web method using AJAX.  That is an industry standard.  It's the same principle as sending form data via POST to a c# method.  It's just being done with a different mode of transit.

@mikesExpertExchange - What you want to avoid is code that misunderstands server side versus client side processing.  So, for example, it is not valid to expect c# code to directly access a variable in jQuery.  Your code isn't doing that.  You're sending the variable from jQuery using AJAX.  That's completely valid.
@zephyr_hex: Thanks for your input/insight. I'll close this question. Thanks to all who contributed in any way.
Thanks to all who contributed in any way.