轻松掌握Ajax.net系列教程三:使用CascadingDropDown组件
【IT168技术文档】
这次我们学习使用AjaxControlToolkit中的CascadingDropDown组件。CascadingDropDown主要是控制数个普通的DropDownList控件,并使它们产生无刷新的级联效果。最常见的用法例如选择地理位置,我们要先选取国家,才能进一步选取所选国家的省份,然后才是城市如此类推。学会CascadingDropDown组件将会大大简化我们开发无刷新级联下拉菜单的流程。
第一步:建立Xml文件和WebService
为了方便我们使用了Xml作为数据源,大家可以参照以下文件格式建立Xml文件。

要使用CascadingDropDown,我们需要建立WebService作为数据传输的载体,因此我们先添加一个WebService并命名为CityService.asmx。
进入CityService.cs文件后我们首先要加上[System.Web.Script.Services.ScriptService()]属性,目的是告诉编译器该WebService需要暴露给客户端使用,否则系统会返回异常。

接着我们需要建立XmlDocument对象,用以返回Xml文件中的数据。
以上代码返回了两个属性,一个是返回XmlDocument对象,一个是返回xml文件的层次,大家按照实际情况编写就可以了。public XmlDocument Document { get { _document = new XmlDocument(); _document.Load(HttpContext.Current.Server.MapPath("~/App_Data/Data.xml")); return _document; } } public string[] Hierarchy { get{ string[] _hierarchy = new string[]{"province", "city"}; return _hierarchy; } }
最后我们写一个简单的函数,用以返回数据源。
[WebMethod] public AjaxControlToolkit.CascadingDropDownNameValue[ ] GetDropDownContents(string knownCategoryValues, string category){ System.Collections.Specialized.StringDictionary knowCategoryValuesDictionary = new System.Collections.Specialized.StringDictionary(); knowCategoryValuesDictionary = AjaxControlToolkit.CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues); return AjaxControlToolkit.CascadingDropDown.QuerySimpleCascadingDropDownDocument(Document, Hierarchy, knowCategoryValuesDictionary, category); }
0
相关文章