ASP.NET MVC传递Model到视图的多种方式总结(一)__通用方式的使用

     有多种方式可以将数据传递到视图,如下所示:

  • ViewData
  • ViewBag
  • PartialView
  • TempData
  • ViewModel
  • Tuple

场景:

     在视图页面,下拉框选择课程触发事件,分别显示老师课程表、学生上课表,如图:

    

     相关的Model:

 1     public class Course
 2     {
 3         public int Id { get; set; }
 4         public string Name { get; set; }
 5     }
 6 
 7     public class Teacher
 8     {
 9         public int Id { get; set; }
10         public string Name { get; set; }
11         public List<Course> Courses { get; set; }
12     }
13 
14     public class Student
15     {
16         public int Id { get; set; }
17         public string Name { get; set; }
18         public List<Course> Courses { get; set; }
19     }

 

 一、使用ViewData传递多个Model

 □ HomeController

1         public ActionResult Index()
2         {
3             ViewData["Courses"] = _repository.GetCourses();
4             ViewData["Students"] = _repository.GetStudents();
5             ViewData["Teachers"] = _repository.GetTeachers();
6             return View();
7         } 

 □ Home/Index.cshtml

 1 @using MvcApplication1.Models
 2 @using System.Web.Helpers;
 3 @{   
 4     Layout = null;
 5 }
 6 
 7 <!DOCTYPE html>
 8 <html>
 9 <head>
10     <meta name="viewport" content="width=device-width" />
11     <title>ViewDataDemo</title>
12     <script src="~/Scripts/jquery-1.8.2.js"></script>
13     <script type="text/javascript">
14         $(function () {
15             //隐藏
16             $('#students').hide();
17             $('#teachers').hide();
18 
19             //点击课程下拉框           
20             $('#sel').change(function() {
21                 selectedCourseName = $('#sel').val().trim();
22                 if (selectedCourseName == "--选择课程--") {
23                     $('#students').hide();
24                     $('#teachers').hide();
25                 } else {
26                     getTeacherTable();
27                     getStudentTable();
28                     $('#students').show();
29                     $('#teachers').show();
30                 }
31             });
32         });
33 
34         var selectedCourseName;
35         //创建老师课程表
36         function getTeacherTable() {
37             $('#teachersTable').empty();
38             $('#teachersTable').append("<table id='tblTeachers'><tr><th>编号</th><th>姓名</th></tr></table>");
39             //把所有老师转换成json格式
40             var teachers = @Html.Raw(Json.Encode(ViewData["Teachers"]));
41             for (var i = 0; i < teachers.length; i++) {
42                 var courses = teachers[i].Courses;
43                 for (var j = 0; j < courses.length; j++) {
44                     if (courses[j].Name == selectedCourseName) {
45                         $('#tblTeachers').append("<tr><td>"+courses[i].Id+"</td><td>"+courses[i].Name+"</td></tr>");
46                     }
47                 }
48             }
49         }
50 
51         //创建学生上课表
52         function getStudentTable() {
53             $('#studentsTable').empty();
54             $('#studentsTable').append("<table id='tblStudents'><tr><th>编号</th><th>姓名</th></tr></table>");
55             var students = @Html.Raw(Json.Encode(ViewData["Students"]));
56             for (var i = 0; i < students.length; i++) {
57                 var courses = students[i].Courses;
58                 for (var j = 0; j < courses.length; j++) {
59                     if (courses[j].Name == selectedCourseName) {
60                         $('#tblStudents').append("<tr><td>"+courses[j].Id+"</td><td>"+courses[j].Name+"</td></tr>");
61                     }
62                 }
63             }
64         }
65     </script>
66 </head>
67 <body>
68     <div>
69         <table>
70             <tr>
71                 <td><h3>选择课程</h3></td>
72                 <td>
73                     <select id="sel">
74                         <option>--选择课程--</option>
75                         @foreach (var course in ViewData["Courses"] as List<Course>)
76                         {
77                             <option>@course.Name</option>
78                         }
79                     </select>
80                 </td>
81             </tr>
82         </table>
83     </div>
84     <div id="teachers">
85         <h4>老师课程表</h4>
86         <div id="teachersTable"></div>
87     </div>
88     <div id="students">
89         <h4>学生上课表</h4>
90         <div id="studentsTable"></div>
91     </div>
92 </body>
93 </html>

 @Html.Raw(Json.Encode(ViewData["Students"]))是把Model转换成json字符串,需要用到System.Web.Helpers,把此类库引用到项目,并且必须设置"复制到本地属性"为true,否则报错。

 

 

二、使用ViewBag传递多个Model

 □ HomeController

1 public ActionResult ViewBagDemo()
2 {
3     ViewBag.Courses = _repository.GetCourses();
4     ViewBag.Students = _repository.GetStudents();
5     ViewBag.Teachers = _repository.GetTeachers();
6     return View();
7 } 

 □ Home/ViewBagDemo.cshtml

下拉框遍历课程改成:
@foreach (var course in ViewBag.Courses)

getTeacherTable()方法中改成:
var teachers = @Html.Raw(Json.Encode(ViewBag.Teachers));

getStudentTable()方法中改成:
var students = @Html.Raw(Json.Encode(ViewBag.Students));

 

三、使用部分视图传递多个Model

 □ HomeController

 1 public ActionResult PartialViewDemo()
 2 {
 3     List<Course> courses = _repository.GetCourses();
 4     return View(courses);
 5 }
 6 
 7 public ActionResult StudentsToPVDemo(string courseName)
 8 {
 9     IEnumerable<Course> courses = _repository.GetCourses();
10     var selectedCourseId = (from c in courses
11                             where c.Name == courseName
12                             select c.Id).FirstOrDefault();
13     IEnumerable<Student> students = _repository.GetStudents();
14     var studentsInCourse = students.Where(s => s.Courses.Any(c => c.Id == selectedCourseId)).ToList();
15     return PartialView("StudentPV", studentsInCourse);
16 }
17 
18 public ActionResult TeachersToPVDemo(string courseName)
19 {
20     IEnumerable<Course> courses = _repository.GetCourses();
21     var selectedCourseId = (from c in courses
22                             where c.Name == courseName
23                             select c.Id).FirstOrDefault();
24     IEnumerable<Teacher> teachers = _repository.GetTeachers();
25     var teachersForCourse = teachers.Where(t => t.Courses.Any(c => c.Id == selectedCourseId)).ToList();
26     return PartialView("TeacherPV", teachersForCourse);
27 } 

 □ Home/PartialViewDemo.cshmtl

 1 @model IEnumerable<MvcApplication1.Models.Course>
 2 @{
 3     Layout = null;
 4 }
 5 <!DOCTYPE html>
 6 <html>
 7 <head>
 8     <meta name="viewport" content="width=device-width" />
 9     <title>PatialViewDemo</title>
10     <script src="~/Scripts/jquery-1.8.2.js"></script>
11     <script type="text/javascript">
12         $(function () {
13             //隐藏
14             $('#students').hide();
15             $('#teachers').hide();
16 
17             //点击课程下拉框           
18             $('#sel').change(function() {
19                 selectedCourseName = $('#sel').val().trim();
20                 if (selectedCourseName == "--选择课程--") {
21                     $('#students').hide();
22                     $('#teachers').hide();
23                 } else {
24                     getTeacherTable();
25                     getStudentTable();
26                     $('#students').show();
27                     $('#teachers').show();
28                 }
29             });
30         });
31 
32         var selectedCourseName;
33         //创建老师课程表
34         function getTeacherTable() {
35             $.ajax({
36                 url: "@Url.Action("TeachersToPVDemo","Home")",
37                 type: 'Get',
38                 data: { courseName: selectedCourseName },
39                 success: function(data) {
40                     $('#teachersTable').empty().append(data);
41                 },
42                 error: function() {
43                     alert("sth wrong");
44                 }
45             });
46         }
47 
48         //创建学生上课表
49         function getStudentTable() {
50             $.ajax({
51                 url: "@Url.Action("StudentsToPVDemo","Home")",
52                 type: 'Get',
53                 data: { courseName: selectedCourseName },
54                 success: function (data) {
55                     $('#studentsTable').empty().append(data);
56                 },
57                 error: function () {
58                     alert("sth wrong");
59                 }
60             });
61         }
62     </script>
63 </head>
64 <body>
65     <div>
66         <table>
67             <tr>
68                 <td><h3>选择课程</h3></td>
69                 <td>
70                     <select id="sel">
71                         <option>--选择课程--</option>
72                         @foreach (var course in Model)
73                         {
74                             <option>@course.Name</option
75                         }
76                     </select>
77                 </td>
78             </tr>
79         </table>
80     </div>
81     <div id="teachers">
82         <h4>老师课程表</h4>
83         <div id="teachersTable"></div>
84     </div>
85     <div id="students">
86         <h4>学生上课表</h4>
87         <div id="studentsTable"></div>
88     </div>
89 </body>
90 </html>

 □ TeacherPV.cshtml与StudentPV.cshtml

 1 @model IEnumerable<MvcApplication1.Models.Teacher>
 2 <table id="tblTeacherDetail">
 3     <tr>
 4         <th>编号</th>
 5         <th>名称</th>
 6     </tr>
 7     @foreach (var item in Model)
 8     {
 9         <tr>
10             <td>@item.Id</td>
11             <td>@item.Name</td>
12         </tr>
13     }
14 </table>

 

四、使用TempData传递多个Model

 □ HomeController

 1 public ActionResult TempDataDemo()
 2 {
 3     //第一次从数据库读取数据放到TempData中,以后的请求从TempData中获取数据
 4     TempData["Courses"] = _repository.GetCourses();
 5     //让TempData保存数据,直到下一次请求
 6     TempData.Keep("Courses");
 7     return View();
 8 }
 9 
10 public ActionResult TeachersTempData(string courseName)
11 {
12     var courses = TempData["Courses"] as IEnumerable<Course>;
13     //由于TempData["Courses"]还要被下一次请求,继续TempData保存数据
14     TempData.Keep("Courses");
15     var selectedCourseId = (from c in courses
16         where c.Name == courseName
17         select c.Id).FirstOrDefault();
18     IEnumerable<Teacher> teachers = _repository.GetTeachers();
19     var teachersForCourse = teachers.Where(t => t.Courses.Any(c => c.Id == selectedCourseId)).ToList();
20     return PartialView("TeacherPV", teachersForCourse);
21 }
22 
23 public ActionResult StudentsTempData(string courseName)
24 {
25     var courses = TempData["Courses"] as IEnumerable<Course>;
26     //由于TempData["Courses"]还要被下一次请求,继续TempData保存数据
27     TempData.Keep("Courses");
28     var selectedCourseId = (from c in courses
29                             where c.Name == courseName
30                             select c.Id).FirstOrDefault();
31     IEnumerable<Student> students = _repository.GetStudents();
32     var studentsForCourse = students.Where(s => s.Courses.Any(c => c.Id == selectedCourseId)).ToList();
33     return PartialView("StudentPV", studentsForCourse);
34 }

□ Home/TempDataDemo.cshtml

下拉框遍历课程:
@foreach (var course in Model)

ajax请求老师课程表:
@Url.Action("TeachersTempData","Home")

ajax请求学生上课表:
@Url.Action("StudentsTempData","Home")

 

五、使用ViewModel传递多个Model

 □ View Model

1 public class SchoolVm
2 {
3     public List<Course> Courses { get; set; }
4     public List<Student> Students { get; set; }
5     public List<Teacher> Teachers { get; set; }
6 }

 □ HomeController

1 public ActionResult ViewModelDemoVM()
2 {
3     SchoolVm vm = new SchoolVm();
4     vm.Courses = _repository.GetCourses();
5     vm.Teachers = _repository.GetTeachers();
6     vm.Students = _repository.GetStudents();
7     return View(vm);
8 }

□ Home/ViewModelDemoVM.cshtml

@model MvcApplication1.Models.SchoolVm

下拉框遍历课程:
@foreach (var course in Model.Courses)

ajax请求老师课程表和学生上课表:
@Html.Raw(Json.Encode(Model.Teachers))
@Html.Raw(Json.Encode(Model.Students))

 

六、使用Tuple传递多个Model

□ HomeController

1 public ActionResult TupleDemo()
2 {
3     var allModels = new Tuple<List<Course>, List<Teacher>, List<Student>>(_repository.GetCourses(),
4         _repository.GetTeachers(), _repository.GetStudents()) {};
5     return View(allModels);
6 }

□ Home/TupleDemo.cshtml

@model Tuple <List <MvcApplication1.Models.Course>, List <MvcApplication1.Models.Teacher>, List <MvcApplication1.Models.Student>>

下拉框遍历课程:
@foreach (var course in Model.Item1)

ajax请求老师课程表和学生上课表:
@Html.Raw(Json.Encode(Model.Item2))
@Html.Raw(Json.Encode(Model.Item3))

参考链接:https://www.codeproject.com/Articles/687061/Using-Multiple-Models-in-a-View-in-ASP-NET-MVC-M

posted on 2018-01-17 14:07  SuperSnowYao  阅读(22905)  评论(6编辑  收藏  举报

导航