ASP.NET中实现无刷新级联

最近在帮学校做一个设备报修系统,由于水平有限,以前做项目的时候很少用到ajax方面的知识,为了实现更好的效果,我查阅了相关资料,参考网上教程写了我下面的程序,不足之处,请多多指正。

开发环境配置为:Visual Studio 2008 Sql  Server 2008

源码下载地址:无刷新级联

1、建立测试数据库

用到两个表,一个所在部门表 Department,一个使用部门表 UseDepart

表:Department

image

表:UseDepart

image

2、新建一个MyClass类

  public class MyClass
  {
      public DataSet GetList(string table, string where)
      {
          string connStr = ConfigurationManager.ConnectionStrings["conn"].ConnectionString;
          using (SqlConnection conn = new SqlConnection(connStr))
          {
              StringBuilder strSql = new StringBuilder();
              strSql.Append("select * from ").Append(table);
              if (!string.IsNullOrEmpty(where))
              {
                  strSql.Append(" where ").Append(where);
              }
              using (SqlCommand cmd = new SqlCommand(strSql.ToString(), conn))
              {
                  conn.Open();
                  DataSet ds = new DataSet();
                  SqlDataAdapter da = new SqlDataAdapter();
                  da.SelectCommand = cmd;
                  da.Fill(ds, "ds");
                  return ds;
              }
          }
      }
  }

3、Default.aspx页面代码JavaScript代码

    <script type="text/javascript">
        $(function() {
            $("#<%=ddlDepartment.ClientID %>").change(
            function() {
                $("#ddlUseDepart").load("LoadUseDepart.aspx?InDepartId=" + $("#" + "<%= ddlDepartment.ClientID %>" + " option:selected").val());
            }
            );
        });
    </script>

4、LoadUseDepart.aspx后台代码

        protected void Page_Load(object sender, EventArgs e)
        {
            int id;
            if (int.TryParse(Request.Params["InDepartId"].ToString(), out id))
            {
                Response.Write(GetUseDepart(id));
                Response.End();
            }
        }

        private string GetUseDepart(int id)
        {
            StringBuilder sb = new StringBuilder();
            DataSet ds = new MyClass().GetList("UseDepart", "DepartId=" + id);
            if (ds.Tables.Count > 0)
            {
                for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
                {
                    sb.Append("<option value='" + ds.Tables[0].Rows[i]["Id"].ToString() + "'>" + ds.Tables[0].Rows[i]["Name"].ToString() + "</option>");
                }
            }
            return sb.ToString();
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值