ASP.NET中實現無重新整理級聯

來源:互聯網
上載者:User

最近在幫學校做一個裝置報修系統,由於水平有限,以前做項目的時候很少用到ajax方面的知識,為了實現更好的效果,我查閱了相關資料,參考網上教程寫了我下面的程式,不足之處,請多多指正。

開發環境配置為:Visual Studio 2008 Sql  Server 2008

源碼:無重新整理級聯

1、建立測試資料庫

用到兩個表,一個所在部門表 Department,一個使用部門表 UseDepart

表:Department

表:UseDepart

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();        }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.