C#C
C#7mo ago
anarchy

✅ "view requires a list but it literally doesn't?"

so I'm doing my teacher's code buut for some reason I got this error when I access my form.cshtml
InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'Exercicios2sem.Models.AlunoViewModel', but this ViewDataDictionary instance requires a model item of type 'System.Collections.Generic.List`1[Exercicios2sem.Models.AlunoViewModel]'.

the thing is... the view doesn't reqires a list type

Form.cshtml
@model Exercicios2sem.Models.AlunoViewModel
@{
    Layout = "~/Views/Shared/_Layout.cshtml";
}
<h2>Cadastro de Aluno</h2>
<form asp-action="Salvar">
    <label asp-for="Id"></label>
    <input asp-for="Id" />
    <br />
    <label asp-for="Nome"></label>
    <input asp-for="Nome" />
    <br />
    <label asp-for="Mensalidade"></label>
    <input asp-for="Mensalidade" />
    <br />
    <label asp-for="DataNascimento"></label>
    <input asp-for="DataNascimento" type="date" />
    <br />
    <label asp-for="CidadeId"></label>
    <input asp-for="CidadeId" />
    <br />
    <input type="submit" value="Salvar" />
</form>


AlunoController.cs
using Exercicios2sem.DAO;
using Exercicios2sem.Models;
using Microsoft.AspNetCore.Mvc;

namespace Exercicios2sem.Controllers
{
    public class AlunoController : Controller
    {
        public IActionResult Index()
        {
            AlunoDAO dao = new AlunoDAO();
            List<AlunoViewModel> lista = dao.Listagem();
            return View(lista);
        }
        public IActionResult Create()
        {
            return View("Form", new AlunoViewModel { DataNascimento = DateTime.Now });
        }

        public IActionResult Salvar(AlunoViewModel aluno)
        {
            AlunoDAO dao = new AlunoDAO();
            dao.Inserir(aluno);
            return RedirectToAction("index");
        }

    }
}
Was this page helpful?