There are many ways of using multiple models in a view, most frequently used are given below:
- ViewData
- ViewModel
- PartialView
- ViewBag
- TempData
- Tuple
All the above ways of using multiple models in view have their place but we need to think and pick which one fits our requirements.
Creating Sample Demo :
Let's get started by creating a sample demo application. Follow the below steps:
MultipleModelDemo
and click OK. MultipleModelDemo
project in solution as shown below in screenshot.
03. Right click on the Models folder, add a Models.cs file. Now we need to add three models named as
Course
, Institute
and Student
by writing the following code as shown below:public class Course
{
public int CourseId { get; set; }
public string CourseName { get; set; }
}
public class Institute
{
public int InstituteId { get; set; }
public string InstituteName { get; set; }
public List<Course> AllotedCourses { get; set; }
}
public class Student
{
public int EnrollmentNo { get; set; }
public string StudentName { get; set; }
public List<Course> EnrolledCourses { get; set; }
}
04. Add a class file under the Models folder named as Repository.cs file, which will have the implementation of methods to get hard-coded data for application in order to keep it convenient.
Following is the code for
GetCourse
method which will return a list of courses.public List<Course> GetCourses()
{
return new List<Course> {
new Course () { CourseId = 1, CourseName = "Chemistry"},
new Course () { CourseId = 2, CourseName = "Physics"},
new Course () { CourseId = 3, CourseName = "Math" },
new Course () { CourseId = 4, CourseName = "Computer Science" }
};
}
Following is the code
GetFaculties
method which will return a list of faculties:
Hide Copy Code
public List<Institute> GetInstitutes()
{
return new List<Institute> {
new Institute() { InstituteId = 1, InstituteName = "SITEM",
AllotedCourses = new List<Course>
{new Course () { CourseId = 1, CourseName = "Chemistry"},
new Course () { CourseId = 2, CourseName = "Medicine"},
new Course () { CourseId = 3, CourseName = "Bussiness Mgmt."},
}},
new Faculty () { InstituteId = 2, InstituteName = "SLIIT" ,
AllotedCourses = new List<Course>
{new Course () { CourseId = 2, CourseName = "Engineering"},
new Course () { CourseId = 4, CourseName = "Computer Science"}
}},
new Faculty () { InstituteId = 3, InstituteName = "NIBM",
AllotedCourses = new List<Course>
{new Course () { CourseId = 3, CourseName = "Software Eng."},
new Course () { CourseId = 4, CourseName = "Hotel Mgmt."}
}}
};
}
Following is the code for
GetStudents
method which will return a list of students:
Hide Copy Code
public List<Student> GetStudents()
{
List<Student> result = new List<Student> {
new Student () { EnrollmentNo = 1, StudentName= "Sumudu",
EnrolledCourses = new List<Course>
{ new Course () { CourseId = 1, CourseName = "Chemistry"},
new Course () { CourseId = 2, CourseName = "Physics"},
new Course () { CourseId = 4, CourseName = "Computer Science"}
}},
new Student () { EnrollmentNo = 2, StudentName= "Lakshan",
EnrolledCourses = new List<Course>
{ new Course () { CourseId = 2, CourseName = "Physics"} ,
new Course ()
{ CourseId = 4, CourseName = "Computer Science"}
}},
new Student () { EnrollmentNo = 3, StudentName= "Sampath",
EnrolledCourses = new List<Course>
{ new Course () { CourseId = 3, CourseName = "Math"},
new Course () { CourseId = 4, CourseName = "Computer Science"}
}}
};
return result;
}
05. Add a
HomeController
to Controller folder. We will write the code in HomeController
later.
06. In Shared folder, we will modify the existing code in _Layout.cshtml file. write the following code in
body
tag:body>
@* Define the place for navigation links in left side of the page*@
<div class="navigationPanel">
<div style="margin: 40px 25px 2px 25px;">
<h3>Links to Demostrations</h3>
So far, we have created basic code which we will be using in all scenarios. Further, we will learn each scenario one by one.
Passing Multiple Models using ViewBag
ViewBag
is also used to pass data from a controller to a view. It is a dynamic property which comes inControllerBase
class that is why it doesn’t require typecasting for datatype
.- Add the following code in
HomeController
:public ActionResult ViewBagDemo() { ViewBag.Courses = _repository.GetCourses(); ViewBag.Students = _repository.GetStudents(); ViewBag.Faculties = _repository.GetFaculties(); return View(); }
HereViewBagDemo
action method will be passing data to view (ViewBagDemo.cshtml) file usingViewBag
. - Add a view named as
ViewBagDemo
. All code will be same as you have written in ViewDataDemo.cshtmlfile. Just modify input model toforeach
function.@*Iterating Course model using ViewBag *@ @foreach (var item in ViewBag.Courses) { <option>@item.CourseName</option>
- In
script
tag, replace the following line of code ingetInstituteTable
function://Get all Institutes with the help of model // (ViewBag.Institutes), and convert data into json format. var allInstitutes = @Html.Raw(Json.Encode(ViewBag.Institutes));
- Replace the following line of code in
getStudentTable
function://Get all students with the help of model(ViewBag.Students), //and convert data into json format. var allStudents = @Html.Raw(Json.Encode(ViewBag.Students));
Passing Multiple Models using PartialView
Partial view is used where you need to share the same code (Razor and HTML code) in more than one view. For more details about
PartialView
, please visit here.- In Home controller, add the following code,
PartialViewDemo
action method will return a view having the list of all courses only. This action method will not have or pass any faculty or student information as of now.public ActionResult PartialViewDemo() { List<Course> allCourse = _repository.GetCourses(); return View(allCourse); }
- Add a view named as
PartialViewDemo
. All HTML code will be same as you have written before. Just modifyforeach
function.@*Iterating Course Model*@ @foreach(var item in Model) { <option>@item.CourseName </option>
- In
script
tag, modifygetInstituteTable
function as written below:function getInstituteTable() { $.ajax({ // Get Institute PartialView url: "/Home/InstituteToPVDemo", type: 'Get', data: { courseName: selectedCourseName }, success: function (data) { $("#InstituteDetailTable").empty().append(data); }, error: function () { alert("something seems wrong"); } }); }
- Modify
getStudentTable
function as written below:function getStudentTable() { $.ajax({ // Get Student PartialView url: "/Home/StudentsToPVDemo", type: 'Get', data: { courseName: selectedCourseName }, success: function (data) { $("#studentDetailTable").empty().append(data); }, error: function () { alert("something seems wrong"); } }); }
- Add a new Action method in
HomeController
asStudentsToPVDemo
and add the following code inStudentsToPVDemo
action method.Hide Copy Codepublic ActionResult StudentsToPVDemo(string courseName) { IEnumerable <Course> allCourses = _repository.GetCourses(); var selectedCourseId = (from c in allCourses where c.CourseName == courseName select c.CourseId).FirstOrDefault(); IEnumerable <Student> allStudents = _repository.GetStudents(); var studentsInCourse = allStudents.Where(s => s.EnrolledCourses.Any(c => c.CourseId == selectedCourseId)).ToList(); return PartialView("StudentPV", studentsInCourse); }