您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關ASP.NET MVC中怎么實現下拉框聯動,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
首先新建好數據庫,表:
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>; } <h3>ProvinceIndex</h3> <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>; } <h3>ProvinceIndex</h3> <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>
好了,弄好之后,運行程序:
選擇一個省份,對應的市的信息就被我們查出來了,綁定到另外的市的下拉框中了。
關于ASP.NET MVC中怎么實現下拉框聯動就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。