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

Interactive image rotator featuring navigation buttons for next and previous slides

I recently followed a tutorial from W3Schools Now, I am looking to enhance it by adding previous / next buttons for the indicators, rather than for the slider itself Here is what I aim to accomplish: https://i.sstatic.net/qH1PQ.png Below is the code sn ...

The Material UI button feature neglects to account for custom CSS styles when attempting to override the default settings

Utilizing a custom bootstrap css styles in my react app, I am seeking to enhance the default material ui components with the bootstrap styles. import React, {useState} from 'react'; import 'cg-bootstrap/core/build/cg-bootstrap-standard.css&a ...

Transforming an ASPX textbox input into HTML formatted text

When I fill out the address textbox in my application for sending an inquiry email, and press enter after each line like the example below: 33A, sector -8, /*Pressed enter Key*/ Sanpada, /*Pressed enter Key*/ Navi mumbai. It should ...

Submitting the form may cause disruptions for others

I currently have an email subscription form for my newsletter that is managed through PHP. This form appears in the footer of every page on my website. Check out a demonstration on JSFIDDLE While the form itself functions properly, I am encountering issu ...

What is the best way to navigate through an HTML node tree, including all of its sub elements, when walking through

Do you know of a way to iterate through the entire hierarchy of HTML elements and check each one for attributes and more without using JavaScript? We currently have a JavaScript solution that iterates through each child element and all their descendants. ...

Unable to locate the specified environment variable in the current nest

Currently, I am referring to the official documentation on the NestJs website that provides a guide on using config files: https://docs.nestjs.com/techniques/configuration Below is the code snippet I am working with: app.module import { Module } from &ap ...

Angular JS Introductory Module

Currently, I am encountering an issue in AngularJS 1.2.15 marked by $injector:modulerr. Interestingly, the application runs smoothly when hosted on a MAMP Apache server locally, but encounters errors when running on a node server, generating the error mess ...

Always keep your phone in landscape orientation for optimal website viewing

Currently, I am facing an issue with my website where it functions perfectly on mobile devices in landscape orientation but elements get distorted when viewed in portrait mode. Is there a method to ensure that the website is always displayed in landscape ...

How to use AJAX to retrieve the text content of an HTML option value?

I have a script that displays a list of values, which I want to write: <option th:each = "iName : ${iNames}" th:value = "${iName}" th:text = "${iName}" th:selected="${selectedIName == iName}" In addition, I have the function setSelectedName in my .j ...

Utilize Modal to Update Information in Laravel

I am looking to implement data editing in Laravel using a modal for viewing, but I am unsure how to retrieve specific data on my edit form. Previously, I built a controller to handle editing data on a separate page without using modals. public function ...

Tips for transferring a calculated value from a child component to a parent component in ReactJs

In my current project, I am faced with the challenge of passing a calculated value from a child component back to its parent. The child component is designed to utilize various user inputs to compute a single value that needs to be returned to the parent. ...

minimize the size of the indigenous foundation input field

Currently incorporating this code snippet into my application: <Item fixedLabel> <Input style={{ width: 0.5 }}/> </Item> The fixedLabel element is extending the entire width of the screen. I have attempted adju ...

Cannot find the appended element in an AJAX call using jQuery

Within the code snippet, .moneychoose is described as the div in moneychoose.jsp. Interestingly, $(".moneychoose") cannot be selected within the ajax call. $("input[name='money']").on("click", function() { if ($("#money").find(".moneychoose" ...

How do I incorporate an external template in Mustache.js?

Welcome, I am a beginner in using Mustache.js. Below is the template and JS code that I have: var template = $('#pageTpl').html(); var html = Mustache.to_html(template, data); $('#sampleArea').html(html); Here is the template ...

Display XML information when a row in the table is selected

I am working with an XML data sheet and utilizing ajax to extract information from it in order to generate specific tabs and construct a table of data. However, I am encountering a challenge when attempting to display details in adjacent divs once a row of ...

Error: The function expressValidator is not recognized in the current environment. This issue is occurring in a project utilizing

I am currently working on building a validation form with Express and node. As a beginner in this field, I encountered an error in my console that says: ReferenceError: expressValidator is not defined index.js code var express = require('express& ...

Is there a way to determine if npm packages are accessing and misusing my system's environment variables?

Apologies if this seems nonsensical. But including a code snippet like this: // to illustrate I'm utilizing a source from https://www.npmjs.com/package/got got.post(maliciousUrl, {json: process.env}) Is it enough to leak environment variables to an u ...

Unable to access the assembly /type?

I have encountered an error in my asp.net mvc application that was previously working fine on IIs. Despite not making any changes to the settings or building the application, it now throws the following error: After noticing the presence of the WebSystem. ...

Koa and Stripe are patiently holding off on displaying the page

My current setup involves using koa and stripe for processing a one-time payment. Although the functionality is there, I'm facing an issue where the page renders before the 'data' assignment takes place. This results in the 'id' sh ...

Insert data into a drop-down menu and organize it

When I choose a value in one Select, the other options are removed and the previous value is added to them. How can I use JQuery to add the previous value to Select and then sort it alphabetically? ...