標籤:opened empty cti dtd 類型 conf 分享圖片 while func
1、說明通過 asp.net,利用jQuery ,c#語言給 select控制項動態載入資料。前端頁面使用的是.aspx類型的HTML頁面,後台使用MVC上的controller控制器
2、webconfig 設定連接字串
<configuration>
<connectionStrings>
<add name="connectStr" connectionString="Data Source=192.168.1.105;Initial Catalog=TestDB;Persist Security Info=True;User ID=sa;pwd=sa;" providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
3、擷取連接字串
public class DBHelper
{
/// <summary>
/// 擷取資料庫連接字串
/// </summary>
/// <returns></returns>
public static string getConnStr()
{
return WebConfigurationManager.ConnectionStrings["connStr"].ToString();
}
}
4、用到的資料表
我這裡的資料表是Oracle中的,大家也可以用sql資料庫
CREATE TABLE "DMKJ_SYSINFO_TS"."T_USER"
( "ID" NUMBER(10,0),
"NAME" VARCHAR2(255 BYTE),
"DESCRIBE" VARCHAR2(255 BYTE)
}
5、前端頁面代碼
說明:需要自己引用jQuery的庫檔案
1 <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="xx.aspx.cs" Inherits="xx.LoginPage" %> 2 3 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 4 <html xmlns="http://www.w3.org/1999/xhtml"> 5 <head> 6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 7 <title></title> 8 //在這裡引入jQuery的庫檔案 9 10 </head>11 <body>12 <div > 13 14 15 <select id="tt01" style=" width: 150px; height: 40px;font-size:17px;line-height: 40px;padding-left: 60px;" >16 </select>17 </div>18 <script type="text/javascript">19 $(function () {20 GetUserList();21 22 });23 function GetUserList() {24 $.post("Login/GetUser", function (data) {25 var table = data; 26 $("#tt01").empty(); //首先清空select現在有的內容27 $("#tt01").append("<option selected=‘selected‘ value=0>請選擇使用者..</option>");28 for (var i = 0; i < table.length; i++) {29 var item = table[i];30 $("#tt01").append("<option value=" + item.id + ">" + item.text + "</option>");31 }32 //返回的是json格式的資料33 }, "json");34 }35 36 </script>37 </body>38 </html>View Code
6、後台代碼
1 public JsonResult GetUser() 2 { 3 string sqlStr = "select * from HYMGS_SYSINFO_FJ.t_office"; 4 OleDbDataReader dr =myExecuteReader(sqlStr); 5 List<OfficeEntity> myList = new List<OfficeEntity>(); 6 while(dr.Read()) 7 { 8 OfficeEntity ob1 = new OfficeEntity() { 9 id = Convert.ToInt32(dr["PID"].ToString()),10 text = dr["NAME"].ToString()11 };12 myList.Add(ob1);13 }14 dr.Close();15 return Json(myList, JsonRequestBehavior.DenyGet);16 }17 18 public static OleDbDataReader myExecuteReader(string strSQL)19 { 20 21 //擷取連接字串22 string strConn=DBHelper.getConnStr();23 OleDbConnection oraCn=new OleDbConnection(strConn) ;24 OleDbCommand OraCmd = new OleDbCommand(strSQL,oraCn);25 try26 {27 oraCn.Open ();28 OleDbDataReader OraDr=OraCmd.ExecuteReader (CommandBehavior.CloseConnection);29 return OraDr;30 }31 32 catch(OleDbException e)33 { 34 throw new Exception(e.Message);35 }36 finally37 {38 //OraCmd.Dispose();39 //oraCn.Close ();40 }41 }View Code
7、實體類
public class UserEntity { public int id { get; set; } public string text { get; set; } }
asp.net c# select 動態載入資料