Summary of ASP.NET MVC's multiple ways of passing Model to view

There are several ways to transfer data to a view, as follows:

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

Scenario:

On the view page, select the course trigger event from the drop-down box, and the teacher's schedule and student's schedule will be displayed respectively, as shown in the figure below:

    

Related models:

 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     }

 

I. use ViewData to transfer multiple models

 □ 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             //hide
16             $('#students').hide();
17             $('#teachers').hide();
18 
19             //Click the course drop-down box           
20             $('#sel').change(function() {
21                 selectedCourseName = $('#sel').val().trim();
22                 if (selectedCourseName == "--Choose a course--") {
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         //Create teacher schedule
36         function getTeacherTable() {
37             $('#teachersTable').empty();
38             $('#teachersTable').append("<table id='tblTeachers'><tr><th>number</th><th>Full name</th></tr></table>");
39             //Turn all teachers into json format
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         //Create student schedule
52         function getStudentTable() {
53             $('#studentsTable').empty();
54             $('#studentsTable').append("<table id='tblStudents'><tr><th>number</th><th>Full name</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>Choose a course</h3></td>
72                 <td>
73                     <select id="sel">
74                         <option>--Choose a course--</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>Teacher schedule</h4>
86         <div id="teachersTable"></div>
87     </div>
88     <div id="students">
89         <h4>Student schedule</h4>
90         <div id="studentsTable"></div>
91     </div>
92 </body>
93 </html>

@ Html.Raw(Json.Encode(ViewData["Students")) is to convert a Model into a JSON string. You need to use System.Web.Helpers to reference such a library to a project, and you must set "copy to local property" to true, otherwise an error will be reported.

 

 

2, Passing multiple models using ViewBag

 □ 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

Change the dropdown box to traverse the course:
@foreach (var course in ViewBag.Courses)

In the getTeacherTable() method, change to:
var teachers = @Html.Raw(Json.Encode(ViewBag.Teachers));

In the getStudentTable() method, change to:
var students = @Html.Raw(Json.Encode(ViewBag.Students));

 

3, Passing multiple models using partial views

 □ 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             //hide
14             $('#students').hide();
15             $('#teachers').hide();
16 
17             //Click the course drop-down box           
18             $('#sel').change(function() {
19                 selectedCourseName = $('#sel').val().trim();
20                 if (selectedCourseName == "--Choose a course--") {
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         //Create teacher schedule
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         //Create student schedule
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>Choose a course</h3></td>
69                 <td>
70                     <select id="sel">
71                         <option>--Choose a course--</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>Teacher schedule</h4>
83         <div id="teachersTable"></div>
84     </div>
85     <div id="students">
86         <h4>Student schedule</h4>
87         <div id="studentsTable"></div>
88     </div>
89 </body>
90 </html>

□ TeacherPV.cshtml and StudentPV.cshtml

 1 @model IEnumerable<MvcApplication1.Models.Teacher>
 2 <table id="tblTeacherDetail">
 3     <tr>
 4         <th>number</th>
 5         <th>Name</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>

 

4, Using TempData to pass multiple models

 □ HomeController

 1 public ActionResult TempDataDemo()
 2 {
 3     //Read data from database for the first time and put it into TempData , later requests from TempData Get data from
 4     TempData["Courses"] = _repository.GetCourses();
 5     //Give Way TempData Save data until next request
 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     //Because TempData["Courses"]And the next request. Go ahead TempData Save data
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     //Because TempData["Courses"]And the next request. Go ahead TempData Save data
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

Drop down box to traverse the course:
@foreach (var course in Model)

ajax requests the teacher's schedule:
@Url.Action("TeachersTempData","Home")

ajax requests the student's class schedule:
@Url.Action("StudentsTempData","Home")

 

5, Passing multiple models using ViewModel

 □ 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

Drop down box to traverse the course:
@foreach (var course in Model.Courses)

ajax requests the teacher schedule and student schedule:
@Html.Raw(Json.Encode(Model.Teachers))
@Html.Raw(Json.Encode(Model.Students))

 

6, Using Tuple to pass multiple models

□ 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>>

Drop down box to traverse the course:
@foreach (var course in Model.Item1)

ajax requests the teacher schedule and student schedule:
@Html.Raw(Json.Encode(Model.Item2))
@Html.Raw(Json.Encode(Model.Item3))

Reference link: https://www.codeproject.com/Articles/687061/Using-Multiple-Models-in-a-View-in-ASP-NET-MVC-M

Tags: ASP.NET JSON JQuery Javascript Database

Posted on Sun, 03 May 2020 05:26:32 -0400 by Jas