【ASP.NET】 MVC下拉框联动
这个case主要是我在做项目的时候遇到一个需要根据input控件输入的内容,动态填充dropdown list中的内容, 实现二者联动的需求。在搜索了一些资源后,这篇博客解决了我的问题,所以记录并转载一下。
转载自: https://www.jb51.net/article/88986.htm
数据库schema:
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
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; } } }
DB Operator:
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>(); } } }
DB转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; } } }
controller:
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); } } }
View:
@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>
Route:
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 } ); }