Übergeben einer Liste von einem Controller an eine Ansicht in ASP.NET Core MVCC#

Ein Treffpunkt für C#-Programmierer
Anonymous
 Übergeben einer Liste von einem Controller an eine Ansicht in ASP.NET Core MVC

Post by Anonymous »

Ich versuche, eine Liste vom Home-Controller an eine Indexansicht zu übergeben, aber wann immer ich mein Programm ausführe, erhalte ich diese Fehlermeldung

InvalidOperationException: Das an ViewDataDictionary übergebene Modellelement ist vom Typ „System.Collections.Generic.List`1[MVCWebApp.Models.Student]“, aber diese ViewDataDictionary-Instanz erfordert ein Modellelement vom Typ 'MVCWebApp.Models.Student'

Kann mir bitte jemand helfen, dieses Problem zu lösen?
Das ist Student< /code> Modellklasse:

Code: Select all

public class Student
{
public int ID { get; private set; }
public string? Name { get; private set; }
public string? Gender { get; private set; }
public string? Branch { get; private set; }
public char? Section { get; private set; }

public Student(int id, string name, string gender, string branch, char section)
{
ID = id;
Name = name;
Gender = gender;
Branch = branch;
Section = section;
}
}//Student
Das ist der HomeController, ich habe die Schülerdaten fest codiert

Code: Select all

public class HomeController : Controller
{
private IEnumerable lstStudents = new List();

public HomeController()
{
lstStudents = new List()
{
new Student(101, "James", "Male", "CSE", 'A'),
new Student(102, "Smith", "Male", "ETC", 'B'),
new Student(103, "David", "Male", "CSE", 'A'),
new Student(104, "Sara", "Female", "CSE", 'A'),
new Student(105, "Pam", "Female", "ETC", 'B')
};
}

public ViewResult Index() => View(lstStudents);
}  //HomeController
Dies ist die Indexansicht:

Code: Select all

@{
ViewData["Title"] = "Home Page";
}

@model List




ID
Name
Gender
Branch
Section



@if(Model.Any())
{
@foreach(Student student in Model)
{

@student?.ID
@student?.Name
@student?.Gender
@student?.Branch
@student?.Section

}
}



Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post