Transferring a JavaScript variable to C# to execute an SQL SELECT query, then sending the returned result back to JavaScript

I am facing an issue while trying to execute code in my Code Behind to query my SQL Server using a JavaScript variable and then return the result as an Integer back to my Javascript.

My approach involves running some Javascript code initially to obtain a variable for the SQL SELECT statement, and then passing it to a hidden ASP field (currently set as a textbox for testing).

Unfortunately, whenever I run the code through refreshHTML(), the value of the hidden field (textbox) appears blank, returning 999999999 instead.

Interestingly, when I run the application, the textbox seems to be populated with the correct value.

Below is the C# code from my Code Behind:

    public int ucount
    {
    get
    {
        if (String.IsNullOrEmpty(invoicenumberhidden.Text))
        {
            return 999999999;
        }

        else { 

        int invoicenumber = int.Parse(invoicenumberhidden.Text);

        string commandText = "SELECT COUNT(*) AS distinct_count FROM (SELECT DISTINCT [inv_section],[invoice_number], [cust_po] FROM [Indigo].[dbo].[invoice_items] WHERE invoice_number=" + invoicenumber + ") AS I;";
        string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Indigo2.Properties.Settings.Constr"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(connectionString))
            using (SqlCommand cmd = new SqlCommand(commandText, conn))
            {
                conn.Open();
                cmd.ExecuteNonQuery();
                int uniquecount = (Int32)cmd.ExecuteScalar();
                conn.Close();
                return uniquecount;
            }
        }          
    }
}

And here is the relevant JavaScript function triggered by an ASP OnClientClick event:

        //Get Primary Key from Grid1
        var grid = jQuery("#<%= JQGrid1.ClientID %>");
        var rowKey = grid.getGridParam("selrow");

        document.getElementById('<%= invoicenumberhidden.ClientID %>').value = rowKey;

        var jsucount = '<%=this.ucount%>';
        alert(jsucount);

This is the relevant ASP code snippet:

<div hidden> <asp:Button ID="btnDownload" runat="server" OnClientClick="refreshHtml();" OnClick="btnDownloadButton_Click" Text="Export PDF"></asp:Button></div>
<asp:TextBox ID="invoicenumberhidden" runat="server"></asp:TextBox>

Answer №1

Swap out

var jsucount = '<%=this.ucount%>';
with
var jsucount = document.getElementById('<%= invoicenumberhidden.ClientID %>').value;
.

The reason for the problem is that in your html page, you have var jsucount = 999999999. This number is being retrieved because .net sets the value of '<%=this.ucount%>' when it sends the page to your browser. Any changes made on the server side will not be reflected.

Update 2:

If you want to perform a server trip to get the latest ucount value, you can use PageMethods.

You can move the ucount logic to a method like GetUCount and annotate it with [WebMethod]. However, you cannot use controls here, so you need to pass the value of the hidden field as a parameter. Additionally, you must make some changes in the javascript code as described below.

Code behind:

[WebMethod]
public int GetUCount(string invoicenumberhidden)
{       
    if (String.IsNullOrEmpty(invoicenumberhidden))
    {
        return 999999999;
    }

    else 
    { 

        int invoicenumber = int.Parse(invoicenumberhidden);

        string commandText = "SELECT COUNT(*) AS distinct_count FROM (SELECT DISTINCT [inv_section],[invoice_number], [cust_po] FROM [Indigo].[dbo].[invoice_items] WHERE invoice_number=" + invoicenumber + ") AS I;";
        string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["Indigo2.Properties.Settings.Constr"].ConnectionString;
            using (SqlConnection conn = new SqlConnection(connectionString))
            using (SqlCommand cmd = new SqlCommand(commandText, conn))
            {
                conn.Open();
                cmd.ExecuteNonQuery();
                int uniquecount = (Int32)cmd.ExecuteScalar();
                conn.Close();
                return uniquecount;
            }
    }               
}

Javascript:

function refreshHtml() {
    //Get Primary Key from Grid1
    var grid = jQuery("#<%= JQGrid1.ClientID %>");
    var rowKey = grid.getGridParam("selrow");

    document.getElementById('<%= invoicenumberhidden.ClientID %>').value = rowKey;

    PageMethods.GetUCount(rowKey, onSuccess, onFailure);        
}

function onSuccess(result) {
    alert(result);
}

function onFailure(result) {
    alert("Failed!");
}

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

What is a memory-saving method to clear an object in JavaScript?

I am looking for a way to use the same object repeatedly in JavaScript by emptying it after its purpose is served, without creating a new object each time. In arrays, I usually do arr.length=0 to clear an array instead of assigning it to a new memory locat ...

Tips for implementing validation in JavaScript

I'm brand new to learning Javascript. Recently, I created a template for a login page and it's working perfectly fine. However, I am struggling with setting up validation and navigation. My goal is to redirect the user to another page if their us ...

Exploring the attributes and functions of JavaScript Objects in an Angular environment

Can Angular's $http.post method recognize JavaScript object properties when sending data? To understand more about JavaScript objects and their properties, visit https://www.w3schools.com/js/js_objects.asp. Here is an example to illustrate my questio ...

Adjusting Bootstrap card content on hover

Currently, I am in the process of developing a website that features a list of products presented in bootstrap cards. I am seeking advice on how to dynamically change the text displayed on these cards when a user hovers over them. Specifically, I want to ...

implementing one active line item at a time in Vue

Within my Vue template, I have a small unordered list: <ul style="border-bottom:none !important; text-decoration:none"> <li class="commentToggle" v-bind:class="{active:commentActive}" v-on:click="setInputName('new')">New Comment ...

Just encountered an issue stating "PrismaClient cannot run in the browser" while working with [Next.js]

My initial plan was to log all the IDs of news in my database using console. However, when I executed the code, an error occurred as shown in this image. What is the best way to address and resolve this issue? https://i.stack.imgur.com/ci8G1.png ...

How to Remove a Dynamically Generated Popover in Angular

As a newcomer to angular, I successfully implemented a bootstrap popover around selected text using the following function: $scope.highlight = function () { var a = document.createElement("a"); a.setAttribute('tabindex', "0"); ...

Managing state changes in React can be a complex task, but

As a newcomer to React, I am currently working on creating an icon menu. However, I am facing an issue with my handleChange function not functioning as expected. While the icon Menu and possibleValues menu are visible, I am unable to select any of the op ...

Stop the change event from occurring on a textarea when the user clicks on an external cancel button

In a particular scenario, there is a textarea with an autosave feature triggered by the change event. When the textarea is focused on, Save and Cancel buttons appear at the bottom, providing users with options in case they prefer not to simply click outsid ...

Transfer spoken words into a textbox using the keyboard-microphone feature on an iPad or mobile device

When we tap on a textbox on an iPad or mobile device in a web browser, the keyboard pops up on the screen. We have the option to choose the microphone and dictate the text directly into the input box using our voice instead of typing. Since speech convers ...

What is the technique for adjusting the background while rotating the corner?

Is it possible to position a background image in the corner while rotating another image? rotate: $('#ship').css({ transform: 'rotate(' + corner + 'deg)' }); } move background: starx[i]=starx[i]+... s ...

Issue with padding in Material UI button component not being applied as expected

I am struggling with applying padding and styles to my Material UI component. Take a look at the code snippet below: import "./css/Landing.css"; import { Button } from "@mui/material"; function Landing() { return ( <div class ...

Incorporate zoom feature into the jQuery polaroid gallery

Currently, I am utilizing a jQuery and CSS3 photo gallery found on this website. My goal is to allow the images to enlarge when clicked, however, the method provided by the author isn't very clear to me, as I'm not an expert in jQuery. I attempt ...

Middleware GPS server - store location and transmit information to the server

After encountering a roadblock with my chosen GPS tracker service not supporting iframe plugins to share my car's position on my website, I've come up with the idea of creating a middleware server. The plan is to gather data from my GPS device, s ...

Tips for simulating an ajax request in a Jasmine test

Check out my code snippet below: function sendRequestData(url, urlParameters) { $.ajax({ url : url, method : 'POST', headers : { 'Accept' : 'application/json' }, contentType : 'application/js ...

Choosing a particular 2D array based on another variable in jQuery and JavaScript

Within my project, I am utilizing 2D arrays to append specific divs under particular circumstances. In an effort to streamline and enhance the code, I attempted to create a variable that would determine which array to utilize based on the id of an HTML < ...

Implementing file change detection using view model in Angular

When using the input type file to open a file and trigger a function on change, you can do it like this: <input type="file" multiple="multiple" class="fileUpload" onchange="angular.element(this).scope().fileOpened(this)" /> The functi ...

Reasons Behind the News Not Being Retrieved Using [XML JS Query]

Can you help me troubleshoot my code? <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>News Site</title> <script> window.document.onload = ...

Efficient Ways to Store Text and Images in Vue.js

I have developed a tool that enables users to upload an image and overlay custom text on it, which can be viewed and edited in the browser. My query is whether it is feasible to save the combined image and text as separate files (e.g., jpg/png) using VueJS ...

Using Inline Styling to Showcase a Background Image in a REACTJS Component

import React from 'react'; import Slick from 'react-slick'; import style from './Slider.module.css'; import {Link} from 'react-router-dom'; const SliderTemplates = (props) => { let template = null; const ...