Derit Agustin Derit Agustin - 3 months ago 27
C# Question

How to Multiple models in one view


public class Student
{
public string Name;
public int Age;
}

List<Student> StudentList = new List<Student>
{
new Student{ Name = "Handri", Age = 8 },
new Student{Name = "Jon Galloway", Age = 10},
new Student{ Name = "Scott Hanselman", Age = 9}
};

public class Teacher
{
public string Name;
public int Age;
}

List<Teacher> TeacherList = new List<TeacherList>
{
new TeacherList { Name = "Jhon", Age = 30 },
new TeacherList {Name = "JANE", Age = 25},
new TeacherList { Name = "Peter", Age = 27}
};



i need multiple view in my models ;

..........................................................................................................................................................

Answer

Using Tuple

A Tuple object is an immutable, fixed-size and ordered sequence object. It is a data structure that has a specific number and sequence of elements. The .NET framework supports tuples up to seven elements.

Using this tuple object we can pass multiple models from the controller to the view.

Controller Code

public ActionResult IndexTuple()
{
    ViewBag.Message = "Welcome to my demo!";
    var tupleModel = new Tuple<List<Teacher>, List<Student>>(GetTeachers(), GetStudents());
    return View(tupleModel);
}

View Code

@using MultipleModelInOneView;
@model Tuple <List<Teacher>, List <Student>>
@{
    ViewBag.Title = "Home Page";
}
<h2>@ViewBag.Message</h2> 
<p><b>Teacher List</b></p>
<table>
    <tr>
        <th>Id</th>
        <th>Code</th>
        <th>Name</th>
    </tr>
    @foreach (Teacher teacher in Model.Item1)
    {
        <tr>
            <td>@teacher.TeacherId</td>
            <td>@teacher.Code</td>
            <td>@teacher.Name</td>
        </tr>
    }
</table>
<p><b>Student List</b></p>
<table>
    <tr>
        <th>Id</th>
        <th>Code</th>
        <th>Name</th>
        <th>Enrollment No</th>
    </tr>
    @foreach (Student student in Model.Item2)
    {
        <tr>
            <td>@student.StudentId</td>
            <td>@student.Code</td>
            <td>@student.Name</td>
            <td>@student.EnrollmentNo</td>
        </tr>
    }
</table>

More details to refer this link http://www.c-sharpcorner.com/UploadFile/ff2f08/multiple-models-in-single-view-in-mvc/