Bind DropDownList from DataTable using AJAX WebMethod

DropDownList Bound from Ajax WebMethod

DropDownList Bound from Ajax WebMethod


We will see one Example to bind one DropDownList using jQuery Ajax and C# WebMethod.

How?

Easy !!!

  • Add a WebMethod to Code Behind page
  • Call to that WebMethod from aspx Page
  • Bind the DropDownList when call succeeds

Let’s see the code

WebMethod

Here we are just creating a Dummy DataTable and converting it to XML.

/// <summary>
/// This WebMethod returns the XML for a DropDownList having value and text.
/// </summary>
/// <param name="tableName">string: Name of the Table having DropDownList items.</param>
/// <returns>string: XML containing all the items.</returns>
[System.Web.Services.WebMethod]
public static string GetDropDownItems(string tableName)
{
    // Create a dummy DataTable.
    DataTable dt = new DataTable(tableName);
    dt.Columns.Add("OptionValue");
    dt.Columns.Add("OptionText");
    dt.Rows.Add("0", "Item 0");
    dt.Rows.Add("1", "Item 1");
    dt.Rows.Add("2", "Item 2");
    dt.Rows.Add("3", "Item 3");
    dt.Rows.Add("4", "Item 4");

    // Convert the DataTable to XML.
    string result;
    using (StringWriter sw = new StringWriter())
    {
        dt.WriteXml(sw);
        result = sw.ToString();
    }

    return result;
}

JavaScript GetDropDownData function

The following function would do a jQuery Ajax call for the WebMethod and bind the Data to the DropDownList.

function GetDropDownData() {
	// Get the DropDownList.
	var ddlTestDropDownListXML = $('#ddlTestDropDownListXML');
	
	// Provide Some Table name to pass to the WebMethod as a paramter.
	var tableName = "someTableName";

	$.ajax({
		type: "POST",
		url: "BindDropDownList.aspx/GetDropDownItems",
		data: '{tableName: "' + tableName + '"}',
		contentType: "application/json; charset=utf-8",
		dataType: "json",
		success: function (response) {
			// Now find the Table from response and loop through each item (row).
			$(response.d).find(tableName).each(function () {
				// Get the OptionValue and OptionText Column values.
				var OptionValue = $(this).find('OptionValue').text();
				var OptionText = $(this).find('OptionText').text();
				
				// Create an Option for DropDownList.
				var option = $("<option>" + OptionText + "</option>");
				option.attr("value", OptionValue);

				ddlTestDropDownListXML.append(option);
			});
		},
		failure: function (response) {
			alert(response.d);
		}
	});
}

Important: We are passing one parameter tableName to the WebMethod, which will be the Dummy Table Name and after conversion to XML, it becomes parent of each Row. Refer the following Screenshot of returned XML Schema as seen inside Firebug Console.

XML returned from WebMethod

XML returned from WebMethod

We can see that someTableName is one one node containing the OptionText and OptionValue of a particular Item. These are actually Rows of the Dummy DataTable before conversion to XML.

Your Inputs !

Will be highly appreciated. Please feel free to comment. If you like the Blog, share this among your friends and colleagues.

Advertisements

6 thoughts on “Bind DropDownList from DataTable using AJAX WebMethod

    • Hey Vu,

      Thanks for reading the Blog and asking me a question. 🙂

      Now, coming to your problem, you just need to use jQuery val() method for this. Suppose, you want to select the “Item 3” given in the Blog above.

      So, inside the Success Method, after populating the DropDownList, you need to set the value. Refer code below…

      success: function (response) {
          // Now find the Table from response and loop through each item (row).
          $(response.d).find(tableName).each(function () {
              // Get the OptionValue and OptionText Column values.
              var OptionValue = $(this).find('OptionValue').text();
              var OptionText = $(this).find('OptionText').text();
                       
              // Create an Option for DropDownList.
              var option = $("<option>" + OptionText + "</option>");
              option.attr("value", OptionValue);
       
              ddlTestDropDownListXML.append(option);
          });
      
          // Select Item 3
          $('#ddlTestDropDownListXML').val(3);
      },

      Demo Here

      I hope it helps.

      Thanks again,
      Tadit

      Like

  1. Hello,
    var OptionValue = $(this).find(‘OptionValue’).text();
    var OptionText = $(this).find(‘OptionText’).text();

    The above gets blank value in chrom. Please help

    Liked by 1 person

    • Hi Mufaddal,

      Thanks for taking interest in the Blog. 🙂

      I don’t have any issues regarding this in Chrome. Did you make any changes to the Project? Have you downloaded and tested the Project I have given here?

      Thanks,
      Tadit

      Like

  2. Hi thank you for this nice example, but i have a problem, when i run in your project file i don’t have any problem but its not work in my project
    var OptionValue = $(this).find(‘id’).text();
    var OptionText = $(this).find(‘name’).text();
    its coming empty [OBJECT object] or undefined. i need some help.

    Liked by 1 person

    • Hi Kadir,

      First of all, thanks a lot for reading the Blog and commenting. 🙂

      Looking at your code, I would like to ask you two questions.
      1. Do you have id and name as two columns of the DataTable in the WebMethod?
      2. Have you checked the XML Schema returned inside Developer Tool (like Firebug) Console? I have given the screenshot in the Blog. Take a look. See what are the nodes. That are actually the column Names and you should read those in jQuery.

      Thanks,
      Tadit

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s