locked
What is the problem with my code it shows error as (An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code) RRS feed

  • Question

  • User-199788946 posted

    The following is the code I have done.

            public ActionResult GetData()
            {
                SchoolEntities2 entities = new SchoolEntities2();
                var query = from Student in entities.Students
                            from Student_Courses in Student.Student_Courses
                            select new
                            {
                                StudentName = Student.Name,
                                CourseName = Student_Courses.Course,
                                EnrolledDate = Student_Courses.DateOfEnrolment                            
                            };
                var res = query.ToList();
                return View(res);
            }

    This is my model 

        public class StudentInfo
        {
            public string Name { get; set; }
            public Nullable<System.DateTime> DateOfEnrolment { get; set; }
    
            public virtual Course Course { get; set; }
        }

    This is my view:

    @model List<WebApplication1.Models.StudentInfo>
    @{
        ViewBag.Title = "GetData";
    }
    
        <table class="table">
            <thead>
                <tr>
                    <th scope="col">Student Name</th>
                    <th scope="col">Course Name</th>
                    <th scope="col">Enrollment Date</th>
                </tr>
            </thead>
            <tbody>
                @foreach (var item in Model)
                {
                    <tr>
                        <th scope="row">1</th>
                        <td>@item.Name</td>
                        <td>@item.Course.CourseName</td>
                        <td>@item.DateOfEnrolment</td>
                    </tr>
                }
    
    
            </tbody>
        </table>

    the error is 

    System.InvalidOperationException: The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[<>f__AnonymousType2`3[System.String,WebApplication1.Models.Course,System.Nullable`1[System.DateTime]]]', but this dictionary requires a model item of type 'System.Collections.Generic.List`1[WebApplication1.Models.StudentInfo]

    I have search on internet but couldn't understand help please

    Friday, April 17, 2020 3:24 PM

Answers

  • User-474980206 posted

    C# is strongly typed, your query returns an list of an anonymous object:

      new { StudentName = Student.Name, CourseName = Student_Courses.Course, EnrolledDate = Student_Courses.DateOfEnrolment }

    not a List<StudentInfo>

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, April 17, 2020 3:29 PM