1. 程式人生 > >ASP.NET MVC下拉框聯動

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 
[email protected]
"; //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 }
 );
}