兩個(gè)DropDownList的聯(lián)動(dòng),選擇其中一個(gè)DropDownList,然后加載數(shù)據(jù)到另外的一個(gè)DropDownList上
這里,我打算實(shí)現(xiàn)的需求是:有兩個(gè)DropDownList,一個(gè)默認(rèn)加載所有的省份數(shù)據(jù),然后,當(dāng)我選擇省份的時(shí)候,把對應(yīng)的市的數(shù)據(jù),綁定到另外一個(gè)DropDownList上面,即實(shí)現(xiàn)了聯(lián)動(dòng)。
好了,這里不打算使用EF了,換用ADO.NET。首先新建好數(shù)據(jù)庫,表:
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
)
--插入測試語句:【在網(wǎng)上找了一個(gè)省市數(shù)據(jù)庫,把里面的數(shù)據(jù)導(dǎo)入我當(dāng)前數(shù)據(jù)庫中】
--開始
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
--結(jié)束
--測試插入成功與否
--SELECT * FROM dbo.Province
--SELECT * FROM dbo.City
然后新建一個(gè)空白的MVC項(xiàng)目,在Model文件夾下,添加兩個(gè)實(shí)體:
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; }
}
}
然后在根目錄下,新建一個(gè)文件夾DBOperator,在里面新建一個(gè)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連接方式訪問數(shù)據(jù)庫
//1.創(chuàng)建連接對象[連接字符串]
SqlConnection conn = new SqlConnection(ConnectionString);
//2.創(chuàng)建命令對象
SqlCommand cmd = new SqlCommand();
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
//3.打開連接
conn.Open();
//4.發(fā)送命令
SqlDataReader reader= cmd.ExecuteReader();
//5.處理數(shù)據(jù)
while (reader.Read())
{
lstProvince.Add(new Province()
{
ProvinceID =Convert.ToInt32( reader["ProvinceID"]),
ProvinceName = reader["ProvinceName"].ToString()
});
}
//6.關(guān)閉連接
conn.Close();
reader.Close();
return lstProvince;
}
/// <summary>
/// 通過ProvinceID獲取市的數(shù)據(jù)
/// </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非連接方式訪問數(shù)據(jù)庫
//1.創(chuàng)建連接對象
SqlConnection conn = new SqlConnection(ConnectionString);
//2.創(chuàng)建數(shù)據(jù)適配器對象
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);//參數(shù)設(shè)置別忘了
//3.打開連接【注意,非鏈接模式下,連接的打開關(guān)閉,無所謂,不過還是打開好點(diǎn)。規(guī)范化】
conn.Open();
//4.發(fā)送命令
sda.Fill(ds);
//5.處理數(shù)據(jù)
//6關(guān)閉連接【【注意,非鏈接模式下,連接的打開關(guān)閉,無所謂,不過還是打開好點(diǎn)。規(guī)范化】】
conn.Close();
return DataTableToList<City>.ConvertToModel(ds.Tables[0]).ToList<City>();
}
}
}
DataTable轉(zhuǎn)List,我在網(wǎng)上找了一個(gè)幫助類:
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;
}
}
}
創(chuàng)建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();
}
}
}
對應(yīng)的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>
修改一下,默認(rèn)的路由,
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 }
);
}
先來看下階段性的成果:運(yùn)行程序:
看,這樣就加載了所有的省份數(shù)據(jù),現(xiàn)在我們要進(jìn)一步實(shí)現(xiàn),選擇一個(gè)省份的時(shí)候,加載數(shù)據(jù)到另外一個(gè)下拉框中。
修改控制器,添加一個(gè)方法:
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>
好了,弄好之后,運(yùn)行程序:
選擇一個(gè)省份,對應(yīng)的市的信息就被我們查出來了,綁定到另外的市的下拉框中了。
總結(jié):這篇文章,雖然基礎(chǔ),但是很重要,平時(shí)開發(fā)中,遇到很多這樣的場景。
還有就是EF用多了,ADO.NET也不能忘記。
連接模式和非鏈接模式查詢數(shù)據(jù)庫6個(gè)步驟,牢記心中。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助