Solved

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

Posted on 2016-07-28
12
118 Views
Last Modified: 2016-08-01
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


my screen shot
0
Comment
Question by:mikesExpertExchange
  • 5
  • 3
  • 2
  • +1
12 Comments
 
LVL 78

Expert Comment

by:David Johnson, CD, MVP
ID: 41734133
I don't suggest mixing aspx and jquery as you are mixing client side and server side technologies
0
 
LVL 8

Expert Comment

by:Prakash Samariya
ID: 41734633
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

0
 
LVL 1

Author Comment

by:mikesExpertExchange
ID: 41734780
@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.
1
 
LVL 42

Expert Comment

by:zephyr_hex
ID: 41734804
@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?
1
 
LVL 42

Expert Comment

by:zephyr_hex
ID: 41734831
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

0
 
LVL 8

Accepted Solution

by:
Prakash Samariya earned 500 total points
ID: 41735444
@mikesExpertExchange, sorry wrong line copied! please try as below:

replace couple of code and test with that! [original code]
return '<a href="StudentAthleteInfo.aspx?StudentID=' + data + '&showweektotal=y" class="glyphicon glyphicon-ok text-center" 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, [original code]
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

1
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 78

Expert Comment

by:David Johnson, CD, MVP
ID: 41736420
Student ID" for that row (see the attached image) gets sent to my C# WebMethod.
he is mixing jquery and a c# web method
0
 
LVL 1

Author Comment

by:mikesExpertExchange
ID: 41736558
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.
0
 
LVL 1

Author Comment

by:mikesExpertExchange
ID: 41736931
@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!
1
 
LVL 42

Expert Comment

by:zephyr_hex
ID: 41737831
@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.
1
 
LVL 1

Author Comment

by:mikesExpertExchange
ID: 41737846
@zephyr_hex: Thanks for your input/insight. I'll close this question. Thanks to all who contributed in any way.
0
 
LVL 1

Author Closing Comment

by:mikesExpertExchange
ID: 41737847
Thanks to all who contributed in any way.
0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

We will take a look at the d3.js library for visualizations.  I will provide a walkthrough of a short bar graph example as well as introduce you to the d3.js API.  We also will explore links of other examples and further information regarding SVG's.
JSON is being used more and more, besides XML, and you surely wanted to parse the data out into SQL instead of doing it in some Javascript. The below function in SQL Server can do the job for you, returning a quick table with the parsed data.
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now