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

使用 jQuery AJAX 在 ASP.NET 中绑定下拉列表

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.78/5 (13投票s)

2013年11月26日

CPOL

1分钟阅读

viewsIcon

141110

downloadIcon

2726

如何在 ASP.NET 中使用 jQuery Ajax 绑定下拉列表

引言

本技巧将帮助您理解如何通过在 ASP.NET 中使用 jQuery AJAX 调用 Web 服务来绑定 DropDownList。 我使用相同的概念在 Web 服务中创建一个 Web 方法,并在 jQuery 中调用这些方法。

Using the Code

首先,您需要在数据库中创建一个示例表。 我在数据库中创建一个国家/地区表。 我们需要在数据库中设计一个表来获取数据。

Sample Image - maximum width is 600 pixels

完成表设计后,在数据库中输入一些国家/地区名称以用于我们的示例。 现在,我们将创建一个 Web 服务中的 Web 方法,并使用该方法从 jQuery 调用它。 您需要按照以下步骤操作。

步骤 1:创建一个 ASP.NET Web 服务

因此,将一个 .asmx 页面添加到当前解决方案并修改代码,如下例所示

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;
namespace Jquery_Webservice
{
    /// <summary>
    /// Summary description for CountryDetails
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, 
    // using ASP.NET AJAX, uncomment the following line. 
    [System.Web.Script.Services.ScriptService]
    public class CountryDetails : System.Web.Services.WebService
    {
        public class CountryInfo
        {
            public int CountryId{get;set;}
            public string CountryName{get;set;}
        }
        public List<countryinfo> CountryInformation { get; set; }
        [WebMethod]
        public List<countryinfo> LoadCountry()
        {
            CountryInfo ci = new CountryInfo();
            List<countryinfo> CountryInformation = new List<countryinfo>();
            DataSet ds;
            using (SqlConnection con = new SqlConnection
            ("Data Source=xxxx;User Id=xxxx;Password=xxxx;DataBase=xxxx"))
            {
                using (SqlCommand cmd = new SqlCommand("select * from Tbl_Country", con))
                {
                    con.Open();
                    cmd.Connection = con;
                    cmd.CommandType = CommandType.Text;
                    using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                    {

                        ds = new DataSet();
                        da.Fill(ds);
                    }
                }
            }
            try
            {
                if (ds != null)
                {
                    if (ds.Tables.Count > 0)
                    {
                        if (ds.Tables[0].Rows.Count > 0)
                        {
                            foreach (DataRow dr in ds.Tables[0].Rows)
                            {
                                CountryInformation.Add(new CountryInfo()
                                {
                                    CountryId = Convert.ToInt32(dr["CountryId"]),
                                    CountryName = dr["CountryName"].ToString()
                                });
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return CountryInformation;
        }
    }
}

不要忘记启用属性

[System.Web.Script.Services.ScriptService] 

在类定义之前。

第二步是在函数定义前添加 [Web Method] 属性。 这样,我们就完成了我们的服务设置。 我们可以运行此服务以在 Web 浏览器中进行测试。 现在,我们将设置一个 jQuery AJAX 函数来调用该服务。

步骤 2:实现 jQuery AJAX

首先,您需要在页面中添加 jQuery 库

$(document).ready(function () {
    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: "CountryDetails.asmx/LoadCountry",
        data: "{}",
        dataType: "json",
        success: function (Result) {
               Result=Result.d;
            $.each(Result, function (key, value) {
                $("#ddlcountry").append($("<option></option>").val
                (value.CountryId).html(value.CountryName));
            });
          // Another way of writing
            //  for (var i = 0; i < Result.length; i++) {
            // $("#ddlcountry").append("<option value=" + Result[i].ID + ">" + 
            //     Result[i].Name + "</option>");
            //  }

          // One more way of writing
            // for (var i in Result) {
            //  $("#ddlcountry").append($("<option></option>").val(Result[i].ID).
            //   text(Result[i].Name));
            //  }

        },
        error: function (Result) {
            alert("Error");
        }
    });
});

关注点

这只是一个简单的演示,用于展示通过 Web 服务绑定 DropDownList 的过程。 在此示例中,我们使用了 SQL Server 数据库、数据适配器和 DataSet。 不要忘记启用属性 [System.Web.Script.Services.ScriptService],并在函数定义前添加 [Web Method] 属性。

© . All rights reserved.