65.9K
CodeProject 正在变化。 阅读更多。
Home

使用 AJAX WebMethod 从 DataTable 绑定下拉列表

2014 年 4 月 16 日

CPOL
viewsIcon

38567

downloadIcon

450

我们将看一个例子,如何使用 jQuery Ajax 和 C# WebMethod 绑定一个下拉列表。

DropDownList Bound from Ajax WebMethod

从 Ajax WebMethod 绑定的下拉列表

我们将看一个例子,如何使用 jQuery AjaxC# WebMethod 绑定一个 下拉列表

如何做到?

很简单 !!!

  • 代码隐藏文件中添加一个 WebMethod
  • aspx 页面调用该 WebMethod
  • 在调用成功时绑定 下拉列表

让我们看看代码

WebMethod

这里,我们只是创建一个虚拟的 DataTable 并将其转换为 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 函数

以下函数将执行一个 jQuery Ajax 调用 WebMethod,并将 数据 绑定到 下拉列表

function GetDropDownData() {
    // Get the DropDownList.
    var ddlTestDropDownListXML = $('#ddlTestDropDownListXML');
    
    // Provide Some Table name to pass to the WebMethod as a parameter.
    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);
        }
    });
}

重要提示:我们正在向 WebMethod 传递一个参数 tableName,它将是虚拟表名,并在转换为 XML 后,它成为每个行的父节点。请参考以下截图中在 Firebug 控制台中看到的返回的 XML 模式。

XML returned from WebMethod

从 WebMethod 返回的 XML

我们可以看到 someTableName 是一个节点,包含特定项目的 OptionTextOptionValue。这些实际上是转换成 XML 之前的虚拟 DataTable 的行。

您的意见!

将不胜感激。请随时评论。如果您喜欢这篇博客,请在您的朋友和同事之间分享它。

使用 AJAX WebMethod 从 DataTable 绑定下拉列表 - CodeProject - 代码之家
© . All rights reserved.