使用Web方法绑定下拉数据,并使用Ajax和WebMethod在Asp.net中绑定Ajax级联下拉列表

时间:2018-06-29 06:30:46

标签: c# jquery asp.net ajax webmethod

我已经使用ajax级联下拉列表绑定了dropdownlist,并使用了web方法,它可以正常工作,并且我能够将国家和州ID保存在数据库中。现在,我想将已保存的ID绑定到填充方法的dropdownlist上,我该如何实现。

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 个答案:

答案 0 :(得分:0)

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

  1. ddlContinents-大陆列表

  2. ddlCountry-国家列表

  3. 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" />

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

在页面的Page_Load事件中,我正在填充大陆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();

    }

}

}

下一步,在父大陆DropDownList的SelectedIndexChanged事件上,我正在根据用户选择的大陆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的记录(国家),然后将其绑定到Country DropDownList

填充城市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();

}

}

上面,我在“城市”表上触发查询,并获取用户选择的属于该国家的所有城市。

显示结果

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

protected void ddlCity_SelectedIndexChanged(object sender, EventArgs e)

{

lblResults.Text = "You Selected " +

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

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

                  ddlCity.SelectedItem.Text;

}