兩個DropDownList的聯動,選擇其中一個DropDownList,然後加載數據到另外的一個DropDownList上
這裡,我打算實現的需求是:有兩個DropDownList,一個默認加載所有的省份數據,然後,當我選擇省份的時候,把對應的市的數據,綁定到另外一個DropDownList上面,即實現了聯動。
好了,這裡不打算使用EF了,換用ADO.NET。首先新建好數據庫,表:
USE master GO IF EXISTS (SELECT * FROM sysdatabases WHERE name='MyAddressDB' ) DROP DATABASE MyAddressDB GO CREATE DATABASE MyAddressDB GO USE MyAddressDB GO IF EXISTS (SELECT * FROM sysobjects WHERE name='Province') DROP TABLE Province GO --省份表 CREATE TABLE Province ( ProvinceID INT IDENTITY(1,1) PRIMARY KEY, ProvinceName NVARCHAR(50) NOT NULL ) IF EXISTS (SELECT * FROM sysobjects WHERE name='City') DROP TABLE City GO --省份表 CREATE TABLE City ( CityID INT IDENTITY(1,1) PRIMARY KEY, CityName NVARCHAR(50) NOT NULL, ProvinceID INT REFERENCES dbo.Province(ProvinceID) NOT NULL ) --插入測試語句:【在網上找了一個省市數據庫,把裡面的數據導入我當前數據庫中】 --開始 INSERT INTO dbo.Province SELECT ProvinceName FROM Temp.dbo.S_Province INSERT INTO dbo.City ( CityName, ProvinceID ) SELECT CityName, ProvinceID FROM Temp.dbo.S_City --結束 --測試插入成功與否 --SELECT * FROM dbo.Province --SELECT * FROM dbo.City
然後新建一個空白的MVC項目,在Model文件夾下,添加兩個實體:
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace JsonDataInMVC.Models { public class Province { public int ProvinceID { get; set; } public string ProvinceName { get; set; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace JsonDataInMVC.Models { public class City { public int CityID { get; set; } public string CityName { get; set; } public int ProvinceID { get; set; } } }
然後在根目錄下,新建一個文件夾DBOperator,在裡面新建一個AddressHelper類
AddRessHelper類中的代碼:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Configuration; using JsonDataInMVC.Models; using System.Data; using System.Data.SqlClient; namespace JsonDataInMVC.DBOperator { public class AddressHelper { /// <summary> /// 連接字符串 /// </summary> public string ConnectionString { get { return ConfigurationManager.ConnectionStrings["DBConnectionString"].ConnectionString; } } /// <summary> /// 獲取所有的省份 /// </summary> /// <returns></returns> public List<Province> GetAllProvince() { List<Province> lstProvince = new List<Province>(); string sql = @"SELECT * FROM dbo.Province"; //ADO.NET連接方式訪問數據庫 //1.創建連接對象[連接字符串] SqlConnection conn = new SqlConnection(ConnectionString); //2.創建命令對象 SqlCommand cmd = new SqlCommand(); cmd.CommandText = sql; cmd.CommandType = CommandType.Text; cmd.Connection = conn; //3.打開連接 conn.Open(); //4.發送命令 SqlDataReader reader= cmd.ExecuteReader(); //5.處理數據 while (reader.Read()) { lstProvince.Add(new Province() { ProvinceID =Convert.ToInt32( reader["ProvinceID"]), ProvinceName = reader["ProvinceName"].ToString() }); } //6.關閉連接 conn.Close(); reader.Close(); return lstProvince; } /// <summary> /// 通過ProvinceID獲取市的數據 /// </summary> /// <param name="id"></param> /// <returns></returns> public List<City> GetCityListByProvinceID(int id) { DataSet ds = new DataSet(); string sql = @"SELECT CityID,CityName FROM dbo.City WHERE ProvinceID=@ProvinceID"; //ADO.NET非連接方式訪問數據庫 //1.創建連接對象 SqlConnection conn = new SqlConnection(ConnectionString); //2.創建數據適配器對象 SqlDataAdapter sda = new SqlDataAdapter(sql,conn);//這裡還真必須這樣寫。不能像下面的兩條注釋語句那樣寫。 //sda.SelectCommand.Connection = conn; //sda.SelectCommand.CommandText = sql; sda.SelectCommand.CommandType = CommandType.Text; sda.SelectCommand.Parameters.AddWithValue("@ProvinceID", id);//參數設置別忘了 //3.打開連接【注意,非鏈接模式下,連接的打開關閉,無所謂,不過還是打開好點。規范化】 conn.Open(); //4.發送命令 sda.Fill(ds); //5.處理數據 //6關閉連接【【注意,非鏈接模式下,連接的打開關閉,無所謂,不過還是打開好點。規范化】】 conn.Close(); return DataTableToList<City>.ConvertToModel(ds.Tables[0]).ToList<City>(); } } }
DataTable轉List,我在網上找了一個幫助類:
using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Reflection; using System.Web; namespace JsonDataInMVC.DBOperator { public static class DataTableToList<T> where T : new() { public static IList<T> ConvertToModel(DataTable dt) { //定義集合 IList<T> ts = new List<T>(); T t = new T(); string tempName = ""; //獲取此模型的公共屬性 PropertyInfo[] propertys = t.GetType().GetProperties(); foreach (DataRow row in dt.Rows) { t = new T(); foreach (PropertyInfo pi in propertys) { tempName = pi.Name; //檢查DataTable是否包含此列 if (dt.Columns.Contains(tempName)) { //判斷此屬性是否有set if (!pi.CanWrite) continue; object value = row[tempName]; if (value != DBNull.Value) pi.SetValue(t, value, null); } } ts.Add(t); } return ts; } } }
創建Province控制器:
using JsonDataInMVC.DBOperator; using JsonDataInMVC.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace JsonDataInMVC.Controllers { public class ProvinceController : Controller { private AddressHelper db; public ProvinceController() { db = new AddressHelper(); } // GET: Province public ActionResult Index() { List<Province> lstProvince= db.GetAllProvince(); ViewBag.ListProvince = lstProvince; return View(); } } }
對應的Index視圖:
@using JsonDataInMVC.Models @{ ViewBag.Title = "Index"; List<Province> lstProvince = ViewBag.ListProvince as List<Province>; } <h2>ProvinceIndex</h2> <label>省份:</label> <select id="myProvince"> @foreach (var item in lstProvince) { <option value="@item.ProvinceID">@item.ProvinceName</option> } </select>
修改一下,默認的路由,
public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( name: "Default", url: "{controller}/{action}/{id}", defaults: new { controller = "Province", action = "Index", id = UrlParameter.Optional } ); }
先來看下階段性的成果:運行程序:
看,這樣就加載了所有的省份數據,現在我們要進一步實現,選擇一個省份的時候,加載數據到另外一個下拉框中。
修改控制器,添加一個方法:
using JsonDataInMVC.DBOperator; using JsonDataInMVC.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace JsonDataInMVC.Controllers { public class ProvinceController : Controller { private AddressHelper db; public ProvinceController() { db = new AddressHelper(); } // GET: Province public ActionResult Index() { List<Province> lstProvince= db.GetAllProvince(); ViewBag.ListProvince = lstProvince; return View(); } public JsonResult GetAllCityByProvinceID(int id) { List<City> lstCity= db.GetCityListByProvinceID(id); return Json(lstCity, JsonRequestBehavior.AllowGet); } } }
Index視圖中:
@using JsonDataInMVC.Models @{ ViewBag.Title = "Index"; List<Province> lstProvince = ViewBag.ListProvince as List<Province>; } <h2>ProvinceIndex</h2> <label>省份:</label> <select id="myProvince"> @foreach (var item in lstProvince) { <option value="@item.ProvinceID">@item.ProvinceName</option> } </select> <br/> <hr /> <label>城市:</label> <select id="myCity"> </select> <script src="~/Scripts/jquery-1.10.2.js"></script> <script type="text/javascript"> $(document).ready(function () { $("#myProvince").change(function () { //獲取省份的ID var provinceID = $("#myProvince").val(); //獲取城市 var myCity=$("#myCity"); //加入測試代碼 debugger; $.ajax({ url: "/Province/GetAllCityByProvinceID/" + provinceID, type: "post", dataType: "json", contentType: "application/json", success: function (result) { var myHTML = ""; myCity.html("");//賦值之前先清空 $.each(result, function (i, data) { myHTML += "<option value=" + data.CityID + ">" + data.CityName + "</option>"; }); myCity.append(myHTML); }, error: function (result) { alert(result.responseText); } }); }) }) </script>
好了,弄好之後,運行程序:
選擇一個省份,對應的市的信息就被我們查出來了,綁定到另外的市的下拉框中了。
總結:這篇文章,雖然基礎,但是很重要,平時開發中,遇到很多這樣的場景。
還有就是EF用多了,ADO.NET也不能忘記。
連接模式和非鏈接模式查詢數據庫6個步驟,牢記心中。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。