(八)学习MVC之三级联动

时间:2023-03-08 16:18:32
(八)学习MVC之三级联动

1.新建项目,MVC选择基本模板

2.新建类:Model/Student.cs,数据库信息有三个实体:分别是年级、班级和学生。

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web; namespace CascadeExample.Models
{
public class Grade
{
[Key]
public int GradeId { get; set; }
public string GradeName { get; set; }
public List<Class> Classes { get; set; } }
public class Class
{
[Key]
public int ClassId { get; set; }
public string ClassName { get; set; }
public int GradeId { get; set; }
public Grade Grades { get; set; }
public List<Student> Students { get;set; }
}
public class Student
{
[Key]
public int StudentId { get; set; }
public string StudentName { get; set; }
public int ClassId { get; set; }
public Class Classes { get; set; }
}
}

3.新建类:Model/StudentContext.cs

using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web; namespace CascadeExample.Models
{
public class StudentContext : DbContext
{
public DbSet<Student> Students { get; set; } //代码中为每个实体都创建了一个DbSet的属性。
public DbSet<Class> Classes { get; set; }
public DbSet<Grade> Grades { get; set; }
public StudentContext()
: base("Connection")
{
Database.CreateIfNotExists(); //表示如果如果不存在此数据库,就去创建数据库。
}
}
}

4.修改Web.Config,数据存放在本地数据库上。

 <connectionStrings>
<add name="Connection" providerName="System.Data.SqlClient" connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=Student;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\Student.mdf" />
</connectionStrings>

5.新建控制器:HomeControl

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CascadeExample.Models; namespace CascadeExample.Controllers
{
public class HomeController : Controller
{
public StudentContext StudentContexts=new StudentContext(); #region 获取年级数据GetGrade() public JsonResult GetGrade()
{
IQueryable<Grade> grades= StudentContexts.Grades;
List<Grade> gradeList = grades.ToList();
List<SelectListItem>gradeListItems=new List<SelectListItem>();
foreach (var i in gradeList)
{
gradeListItems.Add(new SelectListItem{Text = i.GradeName,Value = i.GradeId.ToString()});
}
return Json(gradeListItems, JsonRequestBehavior.AllowGet);
}
#endregion #region 获取班级数据GetClass() public JsonResult GetClass(int id)
{
int gradegradeId = id;
IQueryable<Class> classes = StudentContexts.Classes.Where(o => o.GradeId == gradegradeId);
List<Class> classlList = classes.ToList();
List<SelectListItem> classListItems = new List<SelectListItem>();
foreach (var i in classlList)
{
classListItems.Add(new SelectListItem {Text = i.ClassName,Value = i.ClassId.ToString()});
}
return Json(classListItems, JsonRequestBehavior.AllowGet);
}
#endregion #region 获取学生数据GetStudent() public JsonResult GetStudent(string id)
{
string[] ids = id.Split(",".ToCharArray());
string gradeId = ids[];
string classId = ids[];
int classesId= Convert.ToInt32(classId);
IQueryable<Student> students = StudentContexts.Students.Where(o => o.ClassId == classesId);
List<Student> studentList = students.ToList();
List<SelectListItem>studentListItems=new List<SelectListItem>();
foreach (var i in studentList)
{
studentListItems.Add(new SelectListItem{Text = i.StudentName,Value = i.StudentId.ToString()});
}
return Json(studentListItems, JsonRequestBehavior.AllowGet);
} #endregion #region Index()
public ActionResult Index()
{
return View();
}
#endregion
}
}

6.添加视图:View/Home/Index.cshtml

@model CascadeExample.Models.Grade

@{
ViewBag.Title = "三级联动例子";
Layout = "~/Views/Shared/_Layout.cshtml";
} <fieldset>
<legend>三级联动例子</legend>
<table>
<tr>
<td>
<select id="gradeSelect" name="grade" style="width:100px;">
<option>请选择年级</option>
</select>
</td> <td>
<select id="classSelect" name="classes" style="width:100px;">
<option>请选择班级</option>
</select>
</td> <td>
<select id="studentSelect" name="student" style="width:100px;">
<option>请选择学生</option>
</select>
</td>
</tr>
</table>
<input type="submit" name="submit" id="submit" />
</fieldset>
@section scripts
{
<script type="text/javascript" src="~/Scripts/jquery-ui.min-1.11.1.js"></script>
<script type="text/javascript">
$(document).ready(function () {
GetGrade();
$("#gradeSelect").change(function () {
GetClass();
GetStudent();
});
$("#classSelect").change(function () {
GetStudent();
});
}
); function GetGrade() {
$("#gradeSelect").empty();
var option = $("<option></option>").val(-).text("请选择年级");
$("#gradeSelect").append(option);
$.getJSON("/Home/GetGrade/", function (data) { $.each(data, function (i, item) {
$("<option></option>")
.val(item["Value"])
.text(item["Text"])
.appendTo("#gradeSelect");
});
});
} function GetClass() {
$("#classSelect").empty();
var option = $("<option></option>").val(-).text("请选择班级");
$("#classSelect").append(option);
var url = "/Home/GetClass/" + $("#gradeSelect").val() + "/";
$.getJSON(url, function (data) {
$.each(data, function (i, item) {
$("<option></option>")
.val(item["Value"])
.text(item["Text"])
.appendTo("#classSelect");
});
}); } function GetStudent() {
$("#studentSelect").empty();
var option = $("<option></option>").val(-).text("请选择学生");
$("#studentSelect").append(option);
var url = "/Home/GetStudent/" + $("#gradeSelect").val() + "," + $("#classSelect").val() + "/";
$.getJSON(url, function (data) {
$.each(data, function (i, item) {
$("<option></option>")
.val(item["Value"])
.text(item["Text"])
.appendTo("#studentSelect");
});
});
}
$("#submit").click(function () { var grade = document.getElementById("gradeSelect");
var gradeIndex = grade.selectedIndex; //索引的值
var gradeText = grade.options[gradeIndex].text; //绑定的DataValueField的值
var gradeValue = grade.options[gradeIndex].value; //绑定的DataTextField的值 var classes = document.getElementById("classSelect");
var classesIndex = classes.selectedIndex;
var classText = classes.options[classesIndex].text;
var classesValue = classes.options[classesIndex].value; var student = document.getElementById("studentSelect");
var studentIndex = student.selectedIndex;
var studentText = student.options[studentIndex].text;
var studentValue = student.options[studentIndex].value; if (gradeValue != - && classesValue != - && studentValue != -) {
alert("你的选择是: " + gradeText + classText + studentText + "。");
}
else {
alert("请选择年级、班级和学生信息");
}
});
</script>
}

7.运行程序。

(八)学习MVC之三级联动

8.去数据库添加数据:

年级表:

(八)学习MVC之三级联动

班级表:

(八)学习MVC之三级联动

学生表:

(八)学习MVC之三级联动

9.再次运行程序。

(八)学习MVC之三级联动

(八)学习MVC之三级联动

(八)学习MVC之三级联动

点击提交,出现:

(八)学习MVC之三级联动

10.完成。