使用 ajax 和 webmethod 在 asp.net 中使用 web 方法和 ajax 级联下拉列表绑定下拉数据

Posted

技术标签:

【中文标题】使用 ajax 和 webmethod 在 asp.net 中使用 web 方法和 ajax 级联下拉列表绑定下拉数据【英文标题】:Bind dropdown data using web method and ajax cascading dropdown in asp.net using ajax and webmethod 【发布时间】:2018-12-08 06:51:42 【问题描述】:

我使用 ajax 级联下拉列表绑定下拉列表并使用 web 方法,它运行良好,我能够将国家和州 ID 保存在数据库中现在我想将保存的 ID 绑定到填充方法的下拉列表中,我该如何实现这一点。

Aspx 代码如下:::

<li>
     <asp:DropDownList ID="ddlCountry" runat="server" TabIndex="11"></asp:DropDownList>
     <ajax:CascadingDropDown ID="csdCountry" runat="server" Category="Country" TargetControlID="ddlCountry" PromptText="-- Select Country --" LoadingText=" [Loading Countries...]" ServiceMethod="FetchCountries" ServicePath="~/AjaxCascadingDropDown.asmx"></ajax:CascadingDropDown>
  </li>
  <li>
     <asp:DropDownList ID="ddlState" runat="server" TabIndex="12"></asp:DropDownList>
     <ajax:CascadingDropDown ID="csdState" runat="server"  ParentControlID="ddlCountry" Category="State" TargetControlID="ddlState" PromptText="-- Select State --" LoadingText="[Loading States...]"  ServiceMethod="FetchStates" ServicePath="~/AjaxCascadingDropDown.asmx"></ajax:CascadingDropDown>  
</li>

Web 方法代码如下:::

   [WebMethod]                
        public CascadingDropDownNameValue[] FetchCountries(string knownCategoryValues, string category)
        
            GetLookupResponse countryLookupResponse = commonService.GetLookup("Country");


            List<CascadingDropDownNameValue> countries = new List<CascadingDropDownNameValue>();
            foreach (var countryData in countryLookupResponse.LookupItems)
            
                string CountryID = countryData.ID.ToString();
                string CountryName = countryData.Description.ToString();
                countries.Add(new CascadingDropDownNameValue(CountryName, CountryID));
            
            return countries.ToArray();            
        

    [WebMethod]
        public CascadingDropDownNameValue[] FetchStates(string knownCategoryValues, string category)
        
            int countryId;
            StringDictionary strCountries = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
            countryId = Convert.ToInt32(strCountries["Country"]);
            GetLookupResponse stateLookupResponse = commonService.GetLookup("State");

            List<CascadingDropDownNameValue> states = new List<CascadingDropDownNameValue>();
            foreach (var StateData in stateLookupResponse.LookupItems.Where(id => id.dependencyID == countryId))
            
                string StateID = StateData.ID.ToString();
                string StateName = StateData.Description.ToString();
                states.Add(new CascadingDropDownNameValue(StateName, StateID));
            
            return states.ToArray();
        

填充下拉列表代码 :::

ddlCountry.SelectedValue = address.Country.ID.ToString();
ddlState.SelectedValue = address.State.ID.ToString();
ddlCity.SelectedValue = address.City.ID.ToString();

【问题讨论】:

【参考方案1】:

为每个实体使用 3 个 DropDownLists 一个,映射如下所示

    ddlContinents - 大陆列表

    ddlCountry- 国家列表

    ddlCity - 城市列表

<span style ="font-family:Arial">Select Continent : </span>

<asp:DropDownList ID="ddlContinents" runat="server" AutoPostBack = "true"

             OnSelectedIndexChanged="ddlContinents_SelectedIndexChanged">

<asp:ListItem Text = "--Select Continent--" Value = ""></asp:ListItem>

</asp:DropDownList>

 

<br /><br />

<span style ="font-family:Arial">Select Country : </span>

<asp:DropDownList ID="ddlCountry" runat="server" AutoPostBack = "true"

Enabled = "false"  OnSelectedIndexChanged="ddlCountry_SelectedIndexChanged">

<asp:ListItem Text = "--Select Country--" Value = ""></asp:ListItem>

</asp:DropDownList>

 

<br /><br />

<span style ="font-family:Arial">Select City : </span>

<asp:DropDownList ID="ddlCity" runat="server" AutoPostBack = "true"

 Enabled = "false" OnSelectedIndexChanged="ddlCity_SelectedIndexChanged">

<asp:ListItem Text = "--Select City--" Value = ""></asp:ListItem>

</asp:DropDownList>

 

<br /><br />

<asp:Label ID="lblResults" runat="server" Text="" Font-Names = "Arial" />

为所有 DropDownLists 添加了 OnSelectedIndexChanged 事件,并将 AutoPostBack 属性设置为 true。

在页面的 Page_Load 事件中,我正在填充 Continents DropDownList

protected void Page_Load(object sender, EventArgs e)

if (!IsPostBack)



    ddlContinents.AppendDataBoundItems = true;

    String strConnString = ConfigurationManager

        .ConnectionStrings["conString"].ConnectionString;

    String strQuery = "select ID, ContinentName from Continents";

    SqlConnection con = new SqlConnection(strConnString);

    SqlCommand cmd = new SqlCommand();

    cmd.CommandType = CommandType.Text;

    cmd.CommandText = strQuery;

    cmd.Connection = con;

    try

    

        con.Open();

        ddlContinents.DataSource = cmd.ExecuteReader();

        ddlContinents.DataTextField = "ContinentName";

        ddlContinents.DataValueField = "ID";

        ddlContinents.DataBind();

    

    catch (Exception ex)

    

        throw ex;

    

    finally

    

        con.Close();

        con.Dispose();

    


在父 Continent DropDownList 的 SelectedIndexChanged 事件上,我正在根据用户选择的 Continent 的 ID 填充国家 DropDownList

protected void ddlContinents_SelectedIndexChanged(object sender, EventArgs e)

ddlCountry.Items.Clear();

ddlCountry.Items.Add(new ListItem("--Select Country--", ""));

ddlCity.Items.Clear();

ddlCity.Items.Add(new ListItem("--Select City--", ""));   



ddlCountry.AppendDataBoundItems = true;

String strConnString = ConfigurationManager

    .ConnectionStrings["conString"].ConnectionString;

String strQuery = "select ID, CountryName from Countries " +

                   "where ContinentID=@ContinentID";

SqlConnection con = new SqlConnection(strConnString);

SqlCommand cmd = new SqlCommand();

cmd.Parameters.AddWithValue("@ContinentID",

    ddlContinents.SelectedItem.Value); 

cmd.CommandType = CommandType.Text;

cmd.CommandText = strQuery;

cmd.Connection = con;

try



    con.Open();

    ddlCountry.DataSource = cmd.ExecuteReader();

    ddlCountry.DataTextField = "CountryName";

    ddlCountry.DataValueField = "ID";

    ddlCountry.DataBind();

    if (ddlCountry.Items.Count > 1)

    

        ddlCountry.Enabled = true;

    

    else

    

        ddlCountry.Enabled = false;

        ddlCity.Enabled = false;

    



catch (Exception ex)



    throw ex;



finally



    con.Close();

    con.Dispose();


您会注意到我使用 DropDownList 的 SelectedItemValue 属性将大陆的 ID 作为参数传递给查询,因此查询返回该大陆 ID 的记录(国家),然后绑定到国家 DropDownList

填充城市下拉列表

现在在选择国家时,我将该国家的城市填入 City DropDownList。

protected void ddlCountry_SelectedIndexChanged(object sender, EventArgs e)

ddlCity.Items.Clear();

ddlCity.Items.Add(new ListItem("--Select City--", ""));

ddlCity.AppendDataBoundItems = true;

String strConnString = ConfigurationManager

           .ConnectionStrings["conString"].ConnectionString;

String strQuery = "select ID, CityName from Cities " +

                            "where CountryID=@CountryID";

SqlConnection con = new SqlConnection(strConnString);

SqlCommand cmd = new SqlCommand();

cmd.Parameters.AddWithValue("@CountryID",

                      ddlCountry.SelectedItem.Value);

cmd.CommandType = CommandType.Text;

cmd.CommandText = strQuery;

cmd.Connection = con;

try



    con.Open();

    ddlCity.DataSource = cmd.ExecuteReader();

    ddlCity.DataTextField = "CityName";

    ddlCity.DataValueField = "ID";

    ddlCity.DataBind();

    if (ddlCity.Items.Count > 1)

    

        ddlCity.Enabled = true;

    

    else

    

        ddlCity.Enabled = false;

    





catch (Exception ex)



    throw ex;



finally



    con.Close();

    con.Dispose();


在上面,我在 Cities Table 上发起查询,并获取属于用户选择的那个国家的所有城市。

显示结果

最后,在 City DropDownList 的 SelectedIndexChanged 事件中,我将显示用户完成的完整选择。

protected void ddlCity_SelectedIndexChanged(object sender, EventArgs e)

lblResults.Text = "You Selected " +

                  ddlContinents.SelectedItem.Text + " -----> " +

                  ddlCountry.SelectedItem.Text + " -----> " +

                  ddlCity.SelectedItem.Text;

【讨论】:

以上是关于使用 ajax 和 webmethod 在 asp.net 中使用 web 方法和 ajax 级联下拉列表绑定下拉数据的主要内容,如果未能解决你的问题,请参考以下文章

ASP.NET 3.5 使用 AJAX 调用 [WebMethod] - 500 错误

JQuery ajax调用asp.net的webMethod

使用 jQuery AJAX“401(未经授权)”的 ASP.NET 调用 WebMethod

asp.net-ajax使用-WebMethod使用

带有 ASP.NET WebMethod 的 Jquery AJAX 返回整个页面

Select2 与 Ajax Asp.net 4.0 webmethod 请求