My MVC 5 application inserts into the database, but the view does not display the list of records

Asked

Viewed 72 times

-1

The following error appears: The model item inserted in the dictionary is of type'System.Collections.Generic.List`1[Systemshome.Models.Usuario]', but this dictionary requires an item of type 'Systemshome.Models.Usuario'.

I already searched here about the error and the solution to change in the view to List instead of Ienumerable did not solve. I can put it in the bank, because my Create Action and View work, but Index doesn’t.

My Controller:

namespace Sistemahome.Controllers { public class Usuarioscontroller : Controller { private Banco db = new Banco();

    // GET: Usuarios
    public ActionResult Index()
    {
        return View(db.Usuario.ToList());
    }

    // GET: Usuarios/Details/5
    public ActionResult Details(int? id)
    {
        Usuario usuario = new Usuario();

        if (id > 0)
        {
            usuario = db.Usuario.Find(id);

            if (usuario == null)
            {
                throw new Exception("O registro " + id + " não foi encontrado");
            }
        }
        return View(usuario);
    }

    // GET: Usuarios/Create
    public ActionResult Create()
    {
        var user = new Usuario();

        return View();
    }

My View Index: Imagem da View Index

My Model:

[Table("User")] public partial class Usuario { [System.Diagnostics.Codeanalysis.Suppressmessage("Microsoft.Usage", "CA2214:Donotcalloverridablemethodsinconstructors")] public Usuario() { Historicoproposta = new Hashset(); }

    [Key]
    [Display(Name ="Código do Usuário")]
    public int IDusuario { get; set; }

    [Required]
    [StringLength(100)]
    [Display(Name ="Nome Completo")]
    public string Nome { get; set; }

    [Required]
    [StringLength(50)]
    [Display(Name ="CPF")]
    public string CPF { get; set; }

    [Required]
    [Display(Name ="Data de Nascimento")]
    [DataType(DataType.Date)]
    public DateTime Nasc { get; set; }

    [Required(ErrorMessage = "Informe um usuário válido", AllowEmptyStrings = false)]
    [StringLength(40)]
    [Display(Name ="Login")]
    public string Login_Nome { get; set; }

 //   [Required(ErrorMessage = "Senha Incorreta", AllowEmptyStrings = false)]
    [DataType(System.ComponentModel.DataAnnotations.DataType.Password)]
    [StringLength(10, MinimumLength = 4)]
    [Display(Name ="Senha")]
    public string Senha { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<HistoricoProposta> HistoricoProposta { get; set; }
}

My class of connection to the Bank: public partial class Bank : Dbcontext { public Banco() : base("name=Bank") { }

    public virtual DbSet<Categoria> Categoria { get; set; }
    public virtual DbSet<Fornecedor> Fornecedor { get; set; }
    public virtual DbSet<HistoricoProposta> HistoricoProposta { get; set; }
    public virtual DbSet<PerfilUsuario> PerfilUsuario { get; set; }
    public virtual DbSet<Proposta> Proposta { get; set; }
    public virtual DbSet<StatusTabela> StatusTabela { get; set; }
    public virtual DbSet<Usuario> Usuario { get; set; }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Categoria>()
            .Property(e => e.Tipo)
            .IsUnicode(false);

        modelBuilder.Entity<Fornecedor>()
            .Property(e => e.RazaoSocial)
            .IsUnicode(false);

        modelBuilder.Entity<Fornecedor>()
            .Property(e => e.Cnpj)
            .IsUnicode(false);

        modelBuilder.Entity<Fornecedor>()
            .Property(e => e.Cidade)
            .IsUnicode(false);

        modelBuilder.Entity<PerfilUsuario>()
            .Property(e => e.PerfilTipo)
            .IsUnicode(false);

        modelBuilder.Entity<Proposta>()
            .Property(e => e.NomeProposta)
            .IsUnicode(false);

        modelBuilder.Entity<Proposta>()
            .Property(e => e.Descricao)
            .IsUnicode(false);

        modelBuilder.Entity<Proposta>()
            .Property(e => e.ValorProposta)
            .HasPrecision(18, 0);

        modelBuilder.Entity<Proposta>()
            .Property(e => e.LocalArquivo)
            .IsUnicode(false);

        modelBuilder.Entity<StatusTabela>()
            .Property(e => e.StatusNome)
            .IsUnicode(false);

        modelBuilder.Entity<Usuario>()
            .Property(e => e.Nome)
            .IsUnicode(false);

        modelBuilder.Entity<Usuario>()
            .Property(e => e.CPF)
            .IsUnicode(false);

        modelBuilder.Entity<Usuario>()
            .Property(e => e.Login_Nome)
            .IsUnicode(false);

        modelBuilder.Entity<Usuario>()
            .Property(e => e.Senha)
            .IsUnicode(false);

How can I fix this? Someone can help me?

  • Can you adjust the code? It is deformed inside the script tag. Take advantage and put us your index view. What I’m getting is that you’re only putting Ienumerable... But you need to put your class in List. an example: @model List<User>

  • I put an image of my index view. About your suggestion I tested, but did not solve... @Vainercesario

2 answers

0

Try to force the return of a Ienumerable.

var usuarios = db.Usuario.ToList();
return usuarios.AsEnumerable();

0

In this command you are not seeking from the bank your model. You are taking the users model instance and giving a Tolist().

public ActionResult Index()
{
    return View(db.Usuario.ToList());
}

You need to make an appointment.

public ActionResult Index()
{
   return View(db.Usuario.FindAll().ToList());
}

In your view, that you posted the photo will be at the top of the list of this model of yours:

@model List<SistemaHome.Model.Usuario>
  • thank you so much for the tip, but it didn’t work. I remade my application again keeping the original code and the system worked. I believe it was a bug of VS itself, because the error that it was going through was something that was declared correctly.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.