標籤:items 頁面 strong pen region key 定時 com inline
解決思路:
在資料庫中建立類型字典式表。將下拉框需要添加的項,在資料庫表裡中文、英文名稱對應起來。
下拉框動態綁定資料庫表中需要欄位。
[csharp] view plain copy
- <div id="bgDiv" style="display:none;"></div>
- <a class="btn-lit" href="javascript:" onclick="bgDiv.style.display=‘inline‘;advancedQuery.style.display=‘‘;addItems()"><span>進階查詢</span></a>
在進階查詢單擊事件中,除了顯示查詢方塊外,添加下拉框綁定欄位的函數。此處為addItems().
實現代碼:
[javascript] view plain copy
- <script type="text/javascript">
- //動態綁定下拉框項
- function addItems() {
- $.ajax({
- url: "addItem.ashx/GetItem", //後台webservice裡的方法名稱
- type: "post",
- dataType: "json",
- contentType: "application/json",
- traditional: true,
- success: function (data) {
- for (var i in data) {
- var jsonObj =data[i];
- var optionstring = "";
- for (var j = 0; j < jsonObj.length; j++) {
- optionstring += "<option value=\"" + jsonObj[j].ID + "\" >" + jsonObj[j].chinesename + "</option>";
- }
- $("#dpdField1").html("<option value=‘請選擇‘>請選擇...</option> "+optionstring);
- }
- },
- error: function (msg) {
- alert("出錯了!");
- }
- });
- };
-
- </script>
後台代碼:
[csharp] view plain copy
- public void ProcessRequest(HttpContext context)
- {
- //context.Response.ContentType = "text/plain";
- //context.Response.Write("Hello World");
- GetItem(context);
- }
- public void GetItem(HttpContext context)
- {
- string ReturnValue = string.Empty;
- BasicInformationFacade basicInformationFacade = new BasicInformationFacade(); //執行個體化基礎資訊外觀
- DataTable dt = new DataTable();
- dt = basicInformationFacade.itemsQuery(); //根據查詢條件擷取結果
- ReturnValue = DataTableJson(dt);
- context.Response.ContentType = "text/plain";
- context.Response.Write(ReturnValue);
- //return ReturnValue;
- }
[csharp] view plain copy
- #region dataTable轉換成Json格式
- /// <summary>
- /// dataTable轉換成Json格式
- /// </summary>
- /// <param name="dt"></param>
- /// <returns></returns>
- public string DataTableJson(DataTable dt)
- {
- StringBuilder jsonBuilder = new StringBuilder();
- jsonBuilder.Append("{\"");
- jsonBuilder.Append(dt.TableName.ToString());
- jsonBuilder.Append("\":[");
- for (int i = 0; i < dt.Rows.Count; i++)
- {
- jsonBuilder.Append("{");
- for (int j = 0; j < dt.Columns.Count; j++)
- {
- jsonBuilder.Append("\"");
- jsonBuilder.Append(dt.Columns[j].ColumnName);
- jsonBuilder.Append("\":\"");
- jsonBuilder.Append(dt.Rows[i][j].ToString());
- jsonBuilder.Append("\",");
- }
- jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
- jsonBuilder.Append("},");
- }
- jsonBuilder.Remove(jsonBuilder.Length - 1, 1);
- jsonBuilder.Append("]");
- jsonBuilder.Append("}");
- return jsonBuilder.ToString();
- }
- #endregion
利用Ajax、json給前台頁面中的select綁定資料來源。後台通過兩個函數,分別獲得資料庫表的資料,將資料轉為Json格式返回給前台。前台在接收資料後,將資料進行解析,獲得下拉框中需要綁定的欄位。在綁定時,下拉框的每一項都分別綁定一個文本、value值。文本用於顯示,供使用者選擇。value值,是使用者選擇了某個欄位,取得這個欄位的value值,進行背景查詢欄位。
(轉)Jquery+Ajax實現Select動態定資料