I'm looking to dynamically populate a DropDown list by utilizing Ajax in conjunction with a C# method. Can

Greetings, I have developed a C# method which looks like this:

[WebMethod] 
    protected static void populateDropdown(HiddenField hiddenControl, System.Web.UI.WebControls.DropDownList listinc)
    {
        int data = 0;
        string query;
        data = Convert.ToInt32(hiddenControl.Value);

        SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["default"].ToString());
        connection.Open();
        query = "SELECT DISTINCT incident FROM IncidentReports WHERE period = " + data;
        SqlCommand command = new SqlCommand(query, connection);
        System.Data.DataTable table = new System.Data.DataTable();
        command.CommandTimeout = 36000;
        table.Load(command.ExecuteReader());

        foreach (DataRow row in table.Rows)
        {            
           listinc.Items.Add(row[0].ToString());
        }

    }

I have tested this method using an onclick function and it works perfectly. Now, I need to call it from an Ajax function:

$.ajax({
        type: "POST",
        url: "Homepage.aspx/populateDropdown",
        data: '{hiddenControl , listinc, row }',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(data)
            {
                $.each(data, function (){
                    $("listinc").append($("<option     />").val(this.incident).text(this.row[0]));
                });
            },
            failure: function () {
                alert("Oops! Something went wrong!");
            }
        });

This is my Ajax function, but unfortunately, it is not populating the dropdown list as expected.

Answer №1

It is important to ensure that the list is returned from your WebMethod. I suggest returning a string array from the WebMethod.

    [WebMethod]
    public static string[] populateList()
    {
        // Insert your code here....
        return listinc.ToArray();
    }

Subsequently, in the success function of Ajax:

    $.ajax({
      type: "POST",
      url: "./Inicio.aspx/populateList",
      ...
      success: function (data) {
          let response = data["d"];
          let dropdown = $("#listinc");

          for (let i = 0; i < response.length; i++) {
            // Add your data here
            dropdown.append(`<option>${response[i]}</option>`);
          }
       }
    });

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

Can one recover a Javascript file from a server?

In Python, I am able to extract Javascript code from an HTML file using the code snippet below. import urllib2, jsbeautifier from bs4 import BeautifulSoup f = urllib2.urlopen("http://www.google.com.ph/") soup = BeautifulSoup(f, "lxml") script_raw = str( ...

Concealing Content within an Accordion

Looking for some guidance on setting up a mobile version of my product image with hover features. Currently using tooltips on desktop and planning to use a modified accordion on mobile, but struggling to make progress. Customized some JS to toggle an acco ...

Retrieve information from a template and pass it to a Vue component instance

Being a newcomer to vue, I have a fundamental question. In my template, I have a value coming from a parsed object prop like this: <h1>{{myval.theme}}</h1> The above code displays the value in the browser. However, I want to store this value i ...

Tracking and managing user clicks on external links within a vue.js application

I am currently working on a web application that retrieves data from a CMS. Utilizing the Vue-Router in 'history' mode, I need to address content fetched from the API which may include links. My goal is to manage specific links using the router w ...

When attempting to deserialize JSON in C#, an exception is thrown with the message: "Encountered unexpected character while parsing value: {. Path '', line 1, position 1."

I have searched extensively for answers to my issue on this topic, but none seem to quite match what I am experiencing. Despite attempting various methods such as cleaning the string, replacing double quotes with single quotes, eliminating escape character ...

Utilizing React Material-Table to Trigger a React Component through Table Actions

I have set up a datatable using the code below. <MaterialTable icons={tableIcons} title={title} columns={columns} data={data} actions={[ { icon: () => <Edit />, t ...

Understanding how to access POST content in Meteor.js is an important aspect

In my Meteor app, I am trying to retrieve data using POST requests. Here is the code snippet I am using on the server side: __meteor_bootstrap__.app.stack.splice (0, 0, { route: '/input', handle: function(req, res, next) { req.on(' ...

`Issues with AJAX PHP file upload`

I've been working on an AJAX PHP upload script, but I'm facing some issues. Once the user selects an image to upload, it should display in the specific div container specified in my javascript file (which is working fine). However, I believe ther ...

Is it feasible to commit an object on Vue X through Actions?

I have a question regarding Vue X and actions (with commit). Can an object be passed as input in Commit? Similar to: ... action{ ResetLoginStats({commit}){ commit({ 'SetMutation1':false, 'SetMutation2':true, &a ...

Node was experiencing difficulty locating a module alias that had been defined in the tsconfig file and package.json

I'm currently working on deploying a typescript project in production mode. You can find the code on Github here Executing npm run start:dev launches the server at http://localhost:3000/ Running npm run build generates the dist folder The definitio ...

Locate a specific sequence of characters within an array of objects using JavaScript

I am working with an array of objects, where each object contains a string value. My task is to search for a specific substring within the string. [ { "link": "https://www.sec.gov/Archives/edgar/data/1702510/000170251022000084/00 ...

Tips for preventing issues with Javascript latency causing flash out during page loading in Chrome

When building a page with Vue.js or any other Javascript, the issue of temporary flash during loading on Chrome due to constructing latency can be quite frustrating. This delay is not caused by asynchronous ajax requests, but rather the processing involv ...

use two separate keys for grouping in JavaScript

My current approach involves using the reduce method to organize the data based on the Id of each query. var data = [ {Id: "552", valor: "50.00", Descricao: "Fraldas", }, {Id: "552", valor: "35.00", Descricao: "Creme", }, {Id: "545", valor: "2 ...

Encountering a NoSuchElementException when transitioning from frame[0] to window[1] in Firefox GeckoDriver using Selenium with Python

Encountered an issue with the Firefox GeckoDriver browser where I receive an error stating `element not found`. The problem arises when I navigate from window[1] to frame[0], back to window[1], and then attempt to click the close frame button. I prefer u ...

"Which is the better choice for a Django application's for loop: views.py or

I'm in the process of creating a Django app that features a word list. The app currently utilizes a speech function to inform the user of the first word on the list. The user is then able to record an audio clip of a word they say, which is converted ...

AngularJS input range is written inside the bubble that crosses over the screen

Is there a way to write inside the bubble of the range slider? I have adjusted the design of the range slider and now I simply want to display the number inside the bubble: Please see image for reference I aim to display the number inside a circle. What ...

Visualize data from ajax call in tabular format

I want to display the results of an SQL query in a table using AJAX. I have written code that executes the query during the AJAX call, but when I try to display these values in a table, it shows null values on the div tag. What could be the reason for this ...

Create a script that ensures my website can be set as the homepage on any internet browser

I am currently in search of a way to prompt users on my website to set it as their homepage. Upon clicking "Yes," I would like to execute a script that will automatically make my website the user's browser homepage. I have come across a Similar Thread ...

Removing characters from a string with regular expressions

I need to eliminate instances of << any words #_ from the given text. stringVal = "<<Start words#_ I <<love#_ kind <<man>>, <<john#_ <<kind man>> is really <<great>> <<end words#_ "; The d ...

Obtaining information from a intricate string input

{JSON.stringify(walletData.transactions, null, 2)} My goal is to extract backend data and display it as a table. The response has been converted into an array as shown below. [ { "date": "Nov 07, 2023", "description" ...