Invoke a C# boolean function from Javascript code utilizing PageMethods Go

I am working on a loop that generates buttons and assigns them unique IDs. I want to check if the ID of the button exists in an SQL table, and based on that information, set the color of the button to red or green.

 function InitializeButtons() {
            for (i = 1; i <= 10; i++) {

                var btn = document.createElement("BUTTON");

                btn.id = i ;                    
                btn.style.cssText = 'height:50px;width:50px;margin:5px;';
               if (PageMethods.Check(btn.id) == true)                                      
                {
                    btn.style.cssText ='background:red;height:50px;width:50px;margin:5px;';
                }
                else
                {
                    btn.style.cssText = 'background:green;height:50px;width:50px;margin:5px;';
                }

                document.getElementById("div1").appendChild(btn);
}

The C# function 'Check' below checks if there is a row in the SQL table "Book" with a matching name in the column 'Name' to the passed value 'ID'.

 [System.Web.Services.WebMethod]
        public static bool Check(string ID)
        {
            string connectionString = ConfigurationManager.ConnectionStrings["SimpleDB"].ToString();
            using (SqlConnection con = new SqlConnection(connectionString))
            using (SqlCommand cmd = new SqlCommand(@"
                      IF EXISTS(SELECT 1 FROM Book Where Name = @ID)
                      SELECT 1 ELSE SELECT 0", con))
            {
                con.Open();
                cmd.Parameters.AddWithValue("@ID", ID);
                int result = Convert.ToInt32(cmd.ExecuteScalar());
                return (result == 1);
            }
        }

However, when calling the Check function like this

if (PageMethods.Check(btn.id) == true)  

All buttons end up being green, regardless of whether their IDs match the values in the SQL table column 'Name' or not.

Answer №1

If you're looking to call C# code behind from JavaScript, check out this helpful resource:

Answer №2

make the necessary adjustments to your javascript function

   <script type="text/javascript>
        var buttonElement;
        function initializeFunction() {
            debugger;
            for (var index = 1; index <= 10; index++) {

                buttonElement = document.createElement("BUTTON");

                buttonElement.id = index;
                buttonElement.style.cssText = 'height:50px;width:50px;margin:5px;';
                PageMethods.Check(buttonElement.id, handleSuccess, handleFailure);

            }
        }

        function handleSuccess(data) {
            debugger;
            if (data) {
                buttonElement.style.cssText = 'background:red;height:50px;width:50px;margin:5px;';
            }
            else {
                buttonElement.style.cssText = 'background:green;height:50px;width:50px;margin:5px;';
            }

            document.getElementById("div1").appendChild(buttonElement);
        }

        function handleFailure() {
            alert('Error');
        }

    </script>

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

Accessing JavaScript cookie within .htaccess file to establish redirection parameters according to cookie content

Is there a way to modify the rules within my .htaccess file so that it can properly read a user-side cookie and redirect based on its content? The scenario is this: I have a cookie called userstate which contains an abbreviation of US states, such as AL ( ...

Ways to update the component's state externally

I'm new to Next.js (and React) and I'm attempting to update the state of a component from outside the component. Essentially, I am conditionally rendering HTML in the component and have a button inside the component that triggers a function to se ...

The error message "no match found" can only occur on the server-side when using jQuery version 1.x

Having an issue with this small section of code: $('.desc_container').each(function() { var fulltext = $(this).text(); if(fulltext.length > 50) { var myRegexp = /^(.{47}\w*\W)(.*?)$/g; var match = myRegexp.exec(f ...

Retrieving the final N elements from an array using SQL (Hive)

Looking to extract the X last elements from an array within a column. Here is an example where we aim to extract the last two elements: Column A ['a', 'b', 'c'] ['d', 'e'] ['f&apo ...

Node Express for Advanced Routing

I'm currently developing a web application that will handle CRUD operations on an array within a collection. Here is the structure of the collection model: var mongoose = require('mongoose'); var website = require('./website'); ...

I'm struggling to grasp how to effectively utilize a JSON Object in this situation

In my coding project, I am looking to utilize Javascript in order to create a JSON or array that will house pairs of data for 'id' and 'ip'. This way, if I need to retrieve the 'ip' for a specific 'id=123', I can eas ...

Using React.js to dynamically display or hide elements generated within a component

I'm currently working on a project where I need to dynamically generate form fields based on certain criteria. Specifically, I want to hide some fields and only show them when other specific conditions are met, a common requirement in form designs. Fo ...

What could be causing the issue of receiving the error message: "Uncaught TypeError: Cannot read property 'Title' of undefined"?

I am currently working on developing an AJAX web application. One of the functions I have is aimed at requesting a JSON object and then utilizing it to refresh the website content. Below is the portion of JavaScript causing an issue (Lines 8 - 16): windo ...

Utilizing ng-bind-html to establish Angular bindings within the HTML code

My scenario involves hitting a specific route (#/abc) and then making a POST request to the server to render the HTML received as a response. Instead of embedding this logic directly into $routeProvider.when, I came up with my own solution. This is how I ...

Discovering and updating a DOM element with a rejuvenating touch: Angular JS

Although not very experienced with Angular JS, here's what I currently have and what I aim to achieve: <div ng-app="MyApp" ng-controller="appController"> <div class="input-group"> <input class="form-control enableEnter" type=" ...

Implementing Node Express 4 to efficiently handle response generation from successive API requests

I'm currently in the process of developing a NodeJS server using Express4. The main purpose of this server is to act as a mediator between my frontend Angular app and a 3rd party API. I've set up a specific path that my frontend app can request, ...

Create a QueryBuilder that allows for selecting inputs without the need for filter

Is there a way to adjust the querybuilder functionality without the use of operators? For instance: let filters= []; let filter; filter= { id: 'id', label: 'id', type: 'string' ...

What are the steps to implement session storage within a Puppeteer automation script?

Currently, I am attempting to retrieve the encounter id from a Puppeteer script that launches a browser. These scripts are executed on AWS synthetic canaries. However, when running the script, I encounter the following error: sessionStorage is not define ...

I have attempted every possible solution to identify the reason behind this recurring error. Specifically, I keep encountering a CastError when trying to convert a

Struggling to figure out why this error keeps happening. It's so frustrating! I've been attempting to eliminate the cloudinary upload feature from my website. This should allow users to post on my blog without having to upload an image. Howeve ...

What is the best way to save the city name received from geolocation into a variable and then make an AJAX request?

<script> new Vue({ el: '#fad' , data: { data: {}, }, mounted() { var self = this; navigator.geolocation.getCurrentPosition(success, error); function success(position) { var GEOCO ...

What is the best way to generate an empty object that mimics the structure of an object within an array of objects in AngularJS

I am facing a scenario where I have an array of objects structured like this: $scope.users = [ { ID: "1", Name: "Hege", Username: "Pege", Password: "hp", }, { ID: "2", Name: "Peter", User ...

The canvas's document.getElementById function is unable to find any matching element,

Hello everyone, I am currently diving into the world of javascript and trying to expand my knowledge. However, I have encountered a problem that has me stumped, and I could really use some assistance. While exploring, I came across this page: http://www.w ...

SQL Server Case - Working with Dates

Here is the table data I am working with: ID ActualDt DueDt Flag -- ------- ------- ---- 1 01/03/12 09/13/12 Y 2 NULL 07/12/12 Y 3 NULL 09/12/12 N 4 02/03/12 01/13/12 N I have a specific criteria fo ...

using conditional statements in an app.get() method in express js

app.get('/api/notes/:id', (req, res, next) => { fs.readFile(dataPath, 'utf-8', (err, data) => { if (err) { throw err; } const wholeData = JSON.parse(data); const objects = wholeData.notes; const inputId ...

Leveraging the back button in an AngularJS Mobile SPA

Utilizing AngularJS for my Single Page App (SPA), I am currently exploring the most effective way to handle the back button functionality on mobile devices. My setup involves a single JavaScript file, one HTML page, and no partials. The content is reveale ...