JavaScript, Page Method, and GridView are essential components to creating dynamic and interactive

After learning how to use the page method in JavaScript and ASP.Net (VB.Net), I encountered an issue when trying to insert multiple items into a database using a gridview. Despite my efforts, there were no error messages appearing. Here is what I have so far:

Server-side code (VB)

<WebMethod()> _
    <ScriptMethod()> _
    Public Shared Sub SavetoDB(ByVal ans As Answers)
            Dim constr As String = ConfigurationManager.ConnectionStrings("CCQTConnectionString").ConnectionString
            Using con As New SqlConnection(constr)
                Using cmd As New SqlCommand("INSERT INTO tblApplicantAns (Appnr, QID, answer) VALUES(@Appnr, @QID, @ans)")
                    cmd.CommandType = CommandType.Text
                    cmd.Parameters.AddWithValue("@Appnr", ans.appnr)
                    cmd.Parameters.AddWithValue("@QID", ans.qid)
                    cmd.Parameters.AddWithValue("@ans", ans.ans)
                    cmd.Connection = con
                    con.Open()
                    cmd.ExecuteNonQuery()
                    con.Close()
                End Using
            End Using
        End Sub

Public Class Answers
    Public Property qid() As String
        Get
            Return _qid
        End Get
        Set(ByVal value As String)
            _qid = value
        End Set
    End Property
    Private _qid As String
    Public Property ans() As String
        Get
            Return _ans
        End Get
        Set(ByVal value As String)
            _ans = value
        End Set
    End Property
    Private _ans As String
    Public Property appnr() As String
        Get
            Return _appnr
        End Get
        Set(ByVal value As String)
            _appnr = value
        End Set
    End Property
    Private _appnr As String

JavaScript (AJAX)

$(function () {

var gvDrv = document.getElementById("<%= grdQ.ClientID %>");
           for (i=1; i<gvDrv.rows.length; i++)
           {
             var cell = gvDrv.rows[i].cells;
             var q = cell[0].innerHTML;
             var a = cell[1].innerHTML;

                $("[id*=Button1]").bind("click", function () {
                    var ans = {};
                    ans.appnr = $("[id*=TextBox1]").val();
                    ans.qid = $(" + q + ").val();
                    ans.ans = $(" + a + ").val();
                    $.ajax({
                        type: "POST",
                        url: "English.aspx/SavetoDB",
                        data: '{ans: ' + JSON.stringify(ans) + '}',
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (response) {
                            alert("Time is up! Exam will proceed to next module.");
                            window.location = "Conf_English.aspx";
                        }
                    });
                    return false;
                });
            });
}

Answer №1

When dealing with a single save button for an entire grid, it's crucial to adjust your client-side script logic accordingly. Rather than iterating through the grid elements in reverse order, you should loop through each row upon clicking the button. Here's a revised approach:

$(document).ready(function() {
    $("[id*=Button1]").on("click", function() {
        var gvDrv = document.getElementById("<%= grdQ.ClientID %>");
        for (i = 1; i < gvDrv.rows.length; i++) {
            var cell = gvDrv.rows[i].cells;
            var q = cell[0].innerHTML;
            var a = cell[1].innerHTML;

            var ans = {};
            ans.appnr = $("[id*=TextBox1]").val();
            ans.qid = $(" + q + ").val();
            ans.ans = $(" + a + ").val();
            $.ajax({
                type: "POST",
                url: "English.aspx/SavetoDB",
                data: '{ans: ' + JSON.stringify(ans) + '}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    alert("Time is up! The exam will proceed to the next module.");
                    window.location = "Conf_English.aspx";
                }
            });
        }

        return false;
    });
});

Instead of making individual calls to the page method for each row, consider sending an array of values to the server-side ASP.NET AJAX Page Method. By utilizing the existing Answers class, you can construct a JavaScript array of objects that align with the properties in your class. Here's how you can achieve this:

$(document).ready(function() {
    $("[id*=Button1]").on("click", function() {
        var gvDrv = document.getElementById("<%= grdQ.ClientID %>");
        
        // Create an array to store multiple Answers instances
        var answers = new Array();

        // Iterate over grid rows
        for (i = 1; i < gvDrv.rows.length; i++) {
            var cell = gvDrv.rows[i].cells;
            var q = cell[0].innerHTML;
            var a = cell[1].innerHTML;

            // Formulate an answer object for each row
            var ans = {};
            ans.appnr = $("[id*=TextBox1]").val();
            ans.qid = $(" + q + ").val();
            ans.ans = $(" + a + ").val();

            // Append the answer to the array of answer objects
            answers.push(ans);
        }

        // Call the ASP.NET AJAX Page Method once with the array of answer values
        $.ajax({
            type: "POST",
            url: "English.aspx/SavetoDB",
            data: '{ans: ' + JSON.stringify(answers) + '}',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                alert("Time is up! The exam will proceed to the next module.");
                window.location = "Conf_English.aspx";
            }
        });

        return false;
    });
});

Finally, in the server-side ASP.NET AJAX Page Method, ensure that you handle a list of Answers objects instead of just one. This involves processing each Answers object within the list as shown below:

<WebMethod()>
<ScriptMethod()>
Public Shared Sub SavetoDB(ByVal ans As List(Of Answers))
    Dim constr As String = ConfigurationManager.ConnectionStrings("CCQTConnectionString").ConnectionString

    ' Process each Answers object individually
    For Each answer As Answers In ans   
        Using con As New SqlConnection(constr)
            Using cmd As New SqlCommand("INSERT INTO tblApplicantAns (Appnr, QID, answer) VALUES(@Appnr, @QID, @ans)")
                cmd.CommandType = CommandType.Text
                cmd.Parameters.AddWithValue("@Appnr", answer.appnr)
                cmd.Parameters.AddWithValue("@QID", answer.qid)
                cmd.Parameters.AddWithValue("@ans", answer.ans)
                cmd.Connection = con
                con.Open()
                cmd.ExecuteNonQuery()
                con.Close()
            End Using
        End Using
    Next
End Sub

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Conundrum regarding setting up configuration for express-session middleware in Express version 4.x

Hello, I'm currently diving into node.js and still trying to grasp the concept of configurations in sessions. Below is a basic example of how sessions are used in my app: app.js var express = require('express'); var bodyParser = require(&a ...

JS - What is causing my JavaScript src to not work properly?

Here is a snippet of my code: <form name="calculator"> <input type="button" name="latest" value="You are not using the latest version."> <script src="http://www.alvinneo.com/bulbuleatsfood.js"> if(latest-version==="1.0.4.2"){ document.ca ...

The values stored in UI Router $stateParams can only be accessed and viewed

Currently, I am passing an id to a new state using $stateParams which works well. However, the issue arises when the user reloads the page since there won't be any values in $stateParams. To solve this problem, I decided to store the $stateParam id in ...

Tips for Retrieving Html Element Attributes Using AngularJS

Update: Even though the discussion veered off track, the main question still stands - how can I access an attribute of an HTML element within an Angular controller? Check out my attempt on Plnkr: http://plnkr.co/edit/0VMeFAMEnc0XeQWJiLHm?p=preview // ...

Is there a way for me to duplicate a complex element multiple times within the same page?

As an illustration, let's say I have a social tab located in my header that I would like to duplicate in the footer. This tab is comprised of various buttons with SVG images on top, event listeners linked to button IDs, and CSS styling. One option is ...

Encountering an issue with React npm causing errors that I am unable to resolve

Hey there, I'm a newbie to React. After setting everything up, I encountered an error after running "npm start." Can anyone help me figure out how to fix this? Thanks in advance! Click here for image description ...

Having trouble using the `.not` function in jQuery

I'm working on implementing a collapsible menu using jQuery. When any header is clicked, the next sibling (the box) should expand while all other boxes collapse. HTML <div class="finbox" id="finbox1"> <div class="finheader" id="finheade ...

Update the numerical data within a td element using jQuery

Is there a way to use jquery to increase numerical values in a <td> element? I've attempted the following method without success. My goal is to update the value of the td cell by clicking a button with the ID "#increaseNum". Here is the HTML st ...

span element failed to trigger onload event

I'm encountering a basic issue with my code as a beginner. Below is the HTML snippet: <!DOCTYPE html> <html> <head> <meta http-equiv='content-type' content='text/html; charset=utf8' /> <scrip ...

What is the best way to select and link a specific section of a string using Javascript?

I have a JavaScript string that looks like the following: const pageContent = "He stood up and asked the teacher, "Can you elaborate the last point please?"; My goal is to map out the words in the string and display them in a way that makes ...

What are the different ways I can utilize AJAX in place of an iframe?

Currently, I am utilizing iframes on my website to showcase content from other pages such as forms. However, I am facing an issue on the login page where upon user login with a form inside an iframe, the next page appears within the login iframe which is n ...

Utilizing AngularJS: Binding stateParams value to custom data within state objects

Following the guidelines here, I am setting a page title in my state object. $stateProvider .state('project', { url: '/projects/:origin/:owner/:name', template: '<project></project>', data : { pageTi ...

JQuery may be successfully loaded, but it is not functioning as intended

Just started dabbling in JQuery (I'm a newbie) but I'm having trouble getting it to work! Initially, it worked a couple of times but then suddenly stopped working (pretty strange). I made some changes and now it doesn't work at all. JQuery a ...

Converting javascript html object lowercase

Is there a way to dynamically adjust the height of specific letters in my label? Right now, I am overriding the text for the elements: let element = document.getElementById('xxx') element.textContent = 'Label' I attempted using <sup ...

javascript search for parent function argument

I am struggling to figure out how to locate the key in my json array. When I try to find the key using a function parameter, it does not seem to work. This is a snippet of my json data: ... { "product": [ { "title": " ...

How to retrieve the length of data in Angular without relying on ng-repeat?

I am currently working with Angular and facing a challenge where I need to display the total length of an array without using ng-repeat. Here is the situation: I have a default.json file: { { ... "data": [{ "name":"Test", "erro ...

What is the best way to guide users to different pages on the website without disrupting the socket connection?

I am looking to create a user-friendly web application utilizing socket.io and express. This website will consist of two main pages: the "Rooms" page and the individual "Room" page. The "Rooms" page allows users to input their name, create a new room, or j ...

Utilizing Images with 'General Drawing' in Highcharts

I'm currently attempting to create a task diagram using Highcharts. I had the idea of incorporating images using the <img> tag ren.label('<img src="/images/test.jepg', 10, 82) .attr({ ...

Why is the value returned by getBoundingClientRect 190 when the y attribute is set to 200 in SVG?

When placing textBox1 at a y-position of 200, getBoundingClientRect is returning a value of 190. What could be causing this discrepancy? For more details and code snippets, please refer to the following link: https://codepen.io/anon/pen/REKayR?editors=101 ...

Loss of image quality when utilizing Next/Image in NEXT JS

I am currently developing a web application using Next.js 13, and I recently noticed a decrease in the quality of my images. I'm not sure what went wrong or what I may have missed. Upon inspecting the HTML element on the browser, I found this code: & ...