第一、数据库数据准备(Mysql)
第二、准备 Models 实体;(对应数据库中的数据)
View Code
- 1 public class my_selection 2 {
- 3[Key] 4 public int ID {
- get;
- set;
- }
- 5[StringLength(50)] 6 public string Months {
- get;
- set;
- }
- 7[StringLength(50)] 8 public string Money {
- get;
- set;
- }
- 9 10[StringLength(100)] 11 public string Remark {
- get;
- set;
- }
- 12
- }
第三、准备 Controllers,这边名字是 PayController; 这边主要贴出来两个必备的方法;
View Code
- 1 //
- 2 // GET: /Pay/
- 3
- 4 private UBMRegContext db = new UBMRegContext();
- 5 public ActionResult Payment(string select_month)
- 6 {
- 7 //定义一个泛型;
- 8 var selectionlist = new List<string>();
- 9 var money_values = new List();
- 10 //从数据库中查询mx;
- 11 var mx = from d in db.selectioon orderby d.Months select d.Months;
- 12
- 13
- 14 //将从实体查询的数据添加到泛型之内
- 15
- 16 selectionlist.AddRange(mx.Distinct());
- 17 money_values.Insert(0, new SelectListItem() { Text = "--请选择--", Value = "-1" });
- 18
- 19 //生成列表(将加入的泛型添加到页面便于显示)
- 20 ViewBag.select_month = new SelectList(selectionlist);
- 21 ViewData["Money_value"] = money_values;
- 22 return View();
- 23
- 24
- 25
- 26 }
- 27
- 28 //实现级联
- 29 [HttpGet]
- 30 public ActionResult ShowSecondDropDownList(string FirstLevel)
- 31 {
- 32 var moneys = db.selectioon.Where(x => x.Months == FirstLevel);
- 33 ViewBag.Money_value = moneys;
- 34 return PartialView("Moneyvalue");
- 35 }
第四、最为重要的是 View 的显示页面:当然是刚才创建的 Home 文件夹下的 Views 里面;(我第一个卡点就是 JS,之前 JS 实在是不熟练哈哈。检查了之后测试出来是 html 表头的问题,无敌尴尬。)
这里面有引用到 Ajax,笔者之前对于 Ajax 完全陌生可以说是 0 基础。研究了将近 2 小时才研习透彻。这里面有段代码是 data: {FirstLevel: FirstLevel} 这个参数测试了 N 多变后台的方法获取的方法值就是 null,差点要砸电脑。刚开始第一反应是直接用一个确定的值调试结果还是 null, 后来又开始怀疑是 JS 加载有问题,于是调啊调啊,结果还是 null(接近奔溃); 最后终于参考了别人的方法和官方的说明之后(以后首要地位就是参考官方的文献),{} 里面第一个值代表是后台参数的 string X 是这个 X,":" 后面则是触发的传参值,阿西吧。最后经过 N 多次调试之后终于调通了,感谢祖国。
View Code
- 1 2 "~/Scripts/jquery-1.8.2.min.js" > 3 4 "text/javascript" > 5 6 $(document).ready(init);
- 7
- function init() {
- 8 //当网页上的DOM都载入时,第一层下拉选单也呈现出来了
- 9 10 //當網頁上的DOM都載入時,第一層下拉選單也呈現出來了
- 11 //↓顯示第二層下拉選單,沒加這兩段↓的話,第一次網頁載入時第二層下拉選單不會出現
- 12
- var FirstLevel = $("select[name='selectioon']").val(); //第一層選擇的值
- 13 ShowSecondDropDownList(FirstLevel);
- 14 15 16 $("select[name='selectioon']").change(function() {
- 17
- var FirstLevel = $(this).val(); //获取当前的选择的内容传递给方法ShowCityWithSelectedProvince
- 18 //var FirstLevel = "显示第一行";
- 19 ShowSecondDropDownList(FirstLevel);
- 20
- });
- 21
- }
- 22 23
- function ShowSecondDropDownList(FirstLevel) {
- 24 $.ajax({
- 25 url: "@Url.Action("ShowSecondDropDownList ", "Pay ")",
- 26 type: "get",
- 27 data: {
- FirstLevel: FirstLevel
- },
- 28 async: false,
- 29 success: function(data) {
- 30 $("Money_value").html(data);
- 31
- }
- 32
- });
- 33
- }
- 34 35
第五、使用到的 Razor 语法。级联。
- 1@Html.DropDownList("selectioon", (IEnumerable) ViewData["select_month"], new {
- style = "width:300px; height:30px"
- }) 2@Html.DropDownList("Money_value", (IEnumerable) ViewData["Money_value"], new {
- style = "width:300px; height:30px;"
- })
至此,花了整整 4 个小时才彻底理解通了,反正每天都进一步一点就不算浪费今天的时间,加油吧。
来源: