实现无刷新DropDownList联动效果-ASP教程,数据库相关
来源:作者: 发布时间:2007-12-26 02:08:12


说明:本文在http://blog.csdn.net/cuike519/archive/2004/08/22/81727.aspx文章的基础上做了一点修改。
在做一个文章添加功能时,想在选择大类后,自动将其所属二级小类显示出来,使用dropdownlist的selectedindexchanged事件能够很容易实现,但每次选择后页面总要刷新一次,让人感觉很不爽。为实现dropdownlist无刷新二级联动,这几天在网上找了些资料,但都无法达到我想要的效果,经过反复调试,现已基本实现了此功能,现将代码附下。
一、数据库设计:
字段名 数据类型 说明
classid 自动编号 类编号
classname varchar(8) 类名
upclassid int(4) 上级类编号
classlevel int(4) 类级别,1为大类,2为小类
二、设计步骤:
1、首先,我们新建一个页面droptest.aspx,在其中放入两个dropdownlist控件:dropdownlist1和dropdownlist2,其完整代码如下:
<%@ page language="c#" codebehind="droptest.aspx.cs" autoeventwireup="false" inherits="studyweb.droptest" %>
webform2
该页面的后台文档(dropdownlist1.aspx.cs)中page_load内的代码如下:
if(!this.ispostback)
{
sqlconnection con = new sqlconnection("server=localhost;database=gswebdb;uid=sa;pwd=;");
sqldataadapter da = new sqldataadapter("select classname,classid from classname where classlevel=1",con);
dataset ds = new dataset();
da.fill(ds);
this.dropdownlist1.datasource=ds.tables[0].defaultview;
this.dropdownlist1.datatextfield = "classname";
this.dropdownlist1.datavaluefield = "classid";
this.dropdownlist1.databind();
this.dropdownlist1.attributes.add("onchange","load(this.options[this.selectedindex].value)"); //将classid作为参数传递给脚本函数load(classid),假如要传递的是classname,应将value改为innertext,但假如大类为中文,则调用小类时出现无法显示的问题
// this.dropdownlist2.attributes.add("onchange","javascript:document.form1.th.value=this.options[this.selectedindex].value;"); //读取dropdownlist2的值,将其赋给一个textbox控件th,以获取dropdownlist2的值,为获取dropdownlist2的值,网上有人说可通过使用隐藏的textbox控件来获取,我未能实现,因为在客户端隐藏的textbox控件也是不可用脚本来访问的,没法给其赋值,我只能通过将其样式、字体颜色设于背景相同来达到隐藏效果,这是个很笨的方法,有谁有好的方法,请帮我。
}
此页面实现如下功能:首先从数据库内读取任何类级别为1(即大类)的类名和类编号,绑定到dropdownlist1控件上;然后通过dropdownlist1的attributes属性调用javascript函数load(classid);load()函数通过调用dropchild.aspx页面,读取xml流,得到大类所属小类的classname和classid。
2、新建dropchild.aspx页面文档,其中不插入任何控件和文本,只在其后台文档(dropchild.aspx.cs)中的page_load中加入以下代码:
if(this.request["classid"]!=null)
{
int state = convert.toint32(this.request["classid"]);
sqlconnection con = new sqlconnection("server=localhost;database=gswebdb;uid=sa;pwd=;");
sqldataadapter da = new sqldataadapter("select classname,classid from classname where upclassid="+state+"",con);
dataset ds = new dataset("classname");
da.fill(ds);
xmltextwriter writer = new xmltextwriter(response.outputstream, response.contentencoding);
writer.formatting = formatting.indented;
writer.indentation = 4;
writer.indentchar = ;
ds.writexml(writer);
writer.flush();
response.end();
writer.close();
该方法得到用户选择的大类的编号,通过查询以后得到一个dataset对象,使用该对象的writexml方法直接将内容写到response.outputstream里面然后传递到客户端,客户端的load方法通过result =ohttpreq.responsetext;句话得到一个xml字符串,最后解析此串。
另外,测试获取dropdownlist2值,添加了textbox控件th,当点击button时,处理事件代码如下:
private void button1_click(object sender, system.eventargs e)
{
label1.text=th.text;
}
由于我是初学asp.net,不到之处,请指点一二。
|
还没有关于此文章的相关评论!