MVC: Multiple Models in One Single View

Here the question is say you have two model M1 and M2. M1 model consistd properties like a,b. M2 Consists properties like c,d. All a,b,c, d are required(Tagged as [Required]). Now you have a single View V. You have to display all a,b,c,d four properties into V view.

The simplest solution is first create M1 and M2 model class with a,b[in M1] and c,d[in M2] property . Now in M1 Model have a list property of M2 class

public List<M2> M2Prop { get; set; }

Access M1 Class in V view. You are done. Have a look on the below sample code.

public class Student
    {
        [Required]
        public int RollNo { get; set; }

        [Required]
        public string Name { get; set; }

        [Required]
        public string Class { get; set; }

        public string Address { get; set; }

        public List<StudentScore> StudentScore { get; set; }

   }

And the ‘StudentScore’ class is as follows.

public class StudentScore
    {
        [Required]
        public int StudentRollNo { get; set; }

        [Required]
        public string StudentName { get; set; }

        [Required]
        public string Subject { get; set; }

        [Required]
        public int Marks { get; set; }

        [Required]
        public string Grade { get; set; }

    }

Create View with strongly typed of Student Class.
And on the view it is like below.

@model IEnumerable<MultipleModelInOneView.Models.Student>


@foreach (var item in Model)
    {

<td>
                @item.RollNo
            </td>
            <td>
                @item.Name
            </td>

       @foreach (var score in item.StudentScore)
            {
                 <td>
                    @score.Grade
                  
                </td>
                <td>
                    @score.Marks
                </td>
           
            }

}



You are done. Feel free to post any query.

1 comment: