asp.net 利用微軟資料訪問類庫結合AjaxPro實現無重新整理下拉框級聯

暖楓無敵發表於2012-03-23

1、新建一個web網站,新增如下幾個dll引用。具體的dll檔案可在如下地址下載:http://download.csdn.net/detail/taomanman/4167764


2、新建一個js資料夾,放jquery-1.4.1-vsdoc.js和jquery-1.4.2.min.js兩個js檔案。點選下載:http://download.csdn.net/detail/taomanman/4167768


3、配置Web.config檔案,新增資料庫連線字串及AjaxPro的配置,如下程式碼:

<?xml version="1.0" encoding="utf-8"?>
<!--
  有關如何配置 ASP.NET 應用程式的詳細訊息,請訪問
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <!--新增資料庫連線字串開始-->
  <connectionStrings>
    <add name="MyConnectionString"
     connectionString="Data Source=192.168.2.105;Initial Catalog=資料庫名;User ID=sa;Password=sa" providerName="System.Data.SqlClient" />
  </connectionStrings>
  <!--新增資料庫連線字串結束-->
  <system.web>
    <compilation debug="true" targetFramework="4.0" />
    <!--新增ajaxpro開始-->
    <httpHandlers>
      <add verb="POST,GET" path="ajaxpro/*.ashx" type="AjaxPro.AjaxHandlerFactory,AjaxPro.2"/>
    </httpHandlers>
    <!--新增ajaxpro結束-->
  </system.web>

</configuration>

4、在Default.aspx頁面中新增2個html控制元件select下拉框,新增js檔案,這裡主要是利用AjaxPro實現aspx頁面訪問aspx.cs中的方法,主要程式碼如下:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="AjaxDemo.Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>ajax方式無重新整理級聯下拉</title>
    <script src="js/jquery-1.4.2.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        //頁面載入時執行函式
        $(function () {
            DDL_Init();
        });

        //載入下拉框
        function loadSelect(jsonObj) {
            if (jsonObj == "") {
                return '<option title="-1" selected="selected" value="請選擇">請選擇</option>';
            }
            jsonObj = eval("(" + jsonObj + ")");
            var jsonStr = "";
            $(jsonObj).each(function (key, value) {
                //[{"id": "2011","name": "2011年"}]
                //[{ "id": "2", "name": "第2期" }, { "id": "1", "name": "第1期"}]
                jsonStr += '<option value="' + this.id + '" title="' + (key - 1) + '">' + this.name + '</option>';
            });
            return jsonStr;
        }

        //下拉框恢復
        function resetSelect(selectStr) {
            return '<option title="-1" selected="selected">' + selectStr + '</option>';
        }

        $("#YearID").change(function () {
            var yearValue = $(this).attr("title").val();
            var issueStr;
            if (yearValue == "-1") {
                issueStr += loadSelect(getIssueNumList(yearValue));
            }
            $("#Year_IssumNum").html(issueStr);
        });

        //獲得年份
        function getYearList() {
            //前臺獲取後臺方法,獲得值
            var obj = AjaxDemo.Default.getYearList();
            return obj.value;
        }

        //獲得某個年份下的期
        function getIssueNumList(year) {
            var obj = AjaxDemo.Default.getIssueNumList(year + "");
            return obj.value;
        }

        //初始化下拉控制元件
        function DDL_Init() {
            var year = loadSelect(getYearList());
            //繫結年份
            $("#YearID").append(year);
            //繫結期號
            var issueNum = loadSelect(getIssueNumList($("#YearID option:first").val()));
            $("#Year_IssumNum").append(issueNum);
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    年份:
    <select name="" class="year" id="YearID">
    </select>
    期號:
    <select name="" class="issueNum " id="Year_IssumNum">
    </select>
    </form>
</body>
</html>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AjaxPro;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using System.Data.Common;
using System.Data;

namespace AjaxDemo
{
    public partial class Default : System.Web.UI.Page
    {
        SqlDatabase _db = new SqlDatabase(System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {

            }
            AjaxPro.Utility.RegisterTypeForAjax(typeof(Default));
        }

        [AjaxMethod()]
        public string getYearList()
        {
            string strSQL = "select distinct t.[year] from SeedlingCommentCountyInfo t  order by year desc";
            DbCommand dbcmd = this._db.GetSqlStringCommand(strSQL);
            DataSet ds = _db.ExecuteDataSet(dbcmd);
            string dateStr = "[";
            if (ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow drDate in ds.Tables[0].Rows)
                {
                    dateStr += "{\"id\": \"" + drDate["year"].ToString() + "\",\"name\": \"" + drDate["year"].ToString() + "年\"},";
                }
                dateStr = dateStr.TrimEnd(',') + "]";
            }
            else
            {
                dateStr = "";
            }
            return dateStr;
        }

        [AjaxMethod()]
        public string getIssueNumList(string year)
        {
            string strSQL = "select distinct t.issueNum from SeedlingCommentCountyInfo t where year=" + year + " order by issueNum desc";
            DbCommand dbcmd = this._db.GetSqlStringCommand(strSQL);
            DataSet ds = _db.ExecuteDataSet(dbcmd);
            string issueNumStr = "[";
            if (ds.Tables[0].Rows.Count > 0)
            {
                foreach (DataRow drIssueNum in ds.Tables[0].Rows)
                {
                    issueNumStr += "{\"id\": \"" + drIssueNum["issueNum"].ToString() + "\",\"name\": \"第" + drIssueNum["issueNum"].ToString() + "期\"},";
                }
                issueNumStr = issueNumStr.TrimEnd(',') + "]";
            }
            else
            {
                issueNumStr = "";
            }
            return issueNumStr;
        }
    }
}




相關文章