Finishing an ASP.NET AJAX-based Application - Authoring the Web Service to Supply with Data
(Page 2 of 4 )
Right click the project and choose "Add new item" to create a new Web Service named LocationService.asmx. Next, we will open the LocationService.cs file and create the required web methods.
First, as required by the framework, we must put the ScriptService attribute before the Web Service so that the MS AJAX JavaScript framework will call it correctly:
[System.Web.Script.Services.ScriptService]
Now, let's first define a Web Method named GetCountries, through which we can get the list of countries from DropDownList control named ddlCountry:
[WebMethod]
public CascadingDropDownNameValue[] GetCountries(string knownCategoryValues, string category)
{
List<CascadingDropDownNameValue> countryList = new List<CascadingDropDownNameValue>();
DataSet dsCountry = Country.GetCountries();
foreach (DataRow row in dsCountry.Tables[0].Rows)
{
countryList.Add(new CascadingDropDownNameValue(row["CountryName"].ToString(), row["CountryID"].ToString()));
}
return countryList.ToArray();
}
Note that in this method we invoke the Country.GetCountries() method to get all the related countries' information and use it to populate a list named "countryList."
Next, define another Web Method -- GetStatesForCountry -- through which we can get the list of states for the DropDownList named "ddlState" according to the item selected from the first DropDownList control, named ddlCountry:
[WebMethod]
public CascadingDropDownNameValue[] GetStatesForCountry(string knownCategoryValues, string category)
{
StringDictionary kv = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
List<CascadingDropDownNameValue> stateList = new List<CascadingDropDownNameValue>();
DataSet dsState = State.GetStates(int.Parse(kv["Country"]));
foreach (DataRow row in dsState.Tables[0].Rows)
{
stateList.Add(new CascadingDropDownNameValue(row["StateName"].ToString(), row["StateID"].ToString()));
}
return stateList.ToArray();
}
First, the knownCategoryValues parameter which represents the selected content from the DropDownList ddlCountry is passed into this web method. Second, we resolve this parameter into a StringDictionary object. Third, we get the information about the states associated with the specified country by calling the State.GetStates() method. Finally, an array of the states list is returned.
Next: Adding the CascadingDropDown Control to the Web Page >>
More ASP.NET Articles
More By Xianzhong Zhu