Doubt about using a model in the view

Asked

Viewed 320 times

-4

I have an entity called Request. I created in the Model folder a class that loads Orders, called Getpedidos. Well, when creating the controller, I added a view to Action Index. When I built the view, I made her use the model Getpedidos. When I spin, it makes that mistake:

The template item inserted in the dictionary is from type'System.Collections.Generic.List`1[TSL.domain.Entities.Request]', but this dictionary requires an item like 'System.Collections.Generic.Ienumerable`1[TSL.Models.Getpedidos]'.

Exception Details: System.Invalidoperationexception: The item of model inserted in the dictionary is from type'System.Collections.Generic.List`1[TSL.domain.Entities.Request]', but this dictionary requires an item like 'System.Collections.Generic.Ienumerable`1[TSL.Models.Getpedidos]'.

I understood the mistake, I just don’t know how to change it, I mean, whether or not to use the model Getpedidos

EDIT1

Getpedidos

public class GetPedidos : RepositoryData<Pedido, int>
    {
        public override void Delete(Pedido entity)
        {
            using (var conn = new SqlConnection(StringConnection))
            {
                string sql = "DELETE Pedido Where Id_Pedido=@Id";
                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("@Id", entity.Id);
                try
                {
                    conn.Open();
                    cmd.ExecuteNonQuery();
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }

        public override void DeleteById(int id)
        {
            using (var conn = new SqlConnection(StringConnection))
            {
                string sql = "DELETE Pedido Where Id=@Id";
                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("@Id", id);
                try
                {
                    conn.Open();
                    cmd.ExecuteNonQuery();
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }

        public override List<Pedido> GetAll()
        {
            string sql = "Select Id_Pedido, Id_Cliente, Num_Pedido, Dt_Entrega, Valor_Total FROM Pedido ORDER BY Num_Pedido";
            using (var conn = new SqlConnection(StringConnection))
            {
                var cmd = new SqlCommand(sql, conn);
                List<Pedido> list = new List<Pedido>();
                Pedido p = null;
                try
                {
                    conn.Open();
                    using (var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                    {
                        while (reader.Read())
                        {
                            p = new Pedido();
                            p.Id = (int)reader["Id-Pedido"];
                            p.Numero = reader["Num_Pedido"].ToString();
                            p.DtEntrega = Convert.ToDateTime(reader["Dt_Entrega"]);
                            p.ValorTotal = Convert.ToDecimal(reader["ValorTotal"]);
                            p.IdCliente = (int)reader["Id_Cliente"];
                            list.Add(p);
                        }
                    }
                }
                catch (Exception e)
                {
                    throw e;
                }
                return list;
            }
        }


        public override Pedido GetById(int id)
        {
            using (var conn = new SqlConnection(StringConnection))
            {
                string sql = "Select Id_Pedido, Id_Cliente, Num_Pedido, Dt_Entrega, Valor_Total FROM Pedido WHERE Id_Pedido=@Id";
                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("@Id", id);
                Pedido p = null;
                try
                {
                    conn.Open();
                    using (var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))
                    {
                        if (reader.HasRows)
                        {
                            if (reader.Read())
                            {
                                p = new Pedido();
                                p.Id = (int)reader["Id-Pedido"];
                                p.Numero = reader["Num_Pedido"].ToString();
                                p.DtEntrega = Convert.ToDateTime(reader["Dt_Entrega"]);
                                p.ValorTotal = Convert.ToDecimal(reader["ValorTotal"]);
                                p.IdCliente = (int)reader["Id_Cliente"];
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    throw e;
                }
                return p;
            }
        }

        public override void Save(Pedido entity)
        {
            using (var conn = new SqlConnection(StringConnection))
            {
                string sql = "INSERT INTO Pedido (Id_Cliente, Num_Pedido, Dt_Entrega, Valor_Total) VALUES (@Cliente, @NumPedido, @DtEntrega, @Valor)";
                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("@Cliente", entity.IdCliente);
                cmd.Parameters.AddWithValue("@NumPedido", entity.Numero);
                cmd.Parameters.AddWithValue("@DtEntrega", entity.DtEntrega);
                cmd.Parameters.AddWithValue("@Valor", entity.ValorTotal);
                try
                {
                    conn.Open();
                    cmd.ExecuteNonQuery();
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }

        public override void Update(Pedido entity)
        {
            using (var conn = new SqlConnection(StringConnection))
            {
                string sql = "UPDATE Pedido SET Id_Cliente=@Cliente, Num_Pedido=@Numero, Dt_Entrega=@DtEntrega, Valor_Total=@Valor Where Id_Pedido=@Id";
                SqlCommand cmd = new SqlCommand(sql, conn);
                cmd.Parameters.AddWithValue("@Id", entity.Id);
                cmd.Parameters.AddWithValue("@Cliente", entity.IdCliente);
                cmd.Parameters.AddWithValue("@Numero", entity.Numero);
                cmd.Parameters.AddWithValue("@DtEntrega", entity.DtEntrega);
                cmd.Parameters.AddWithValue("@Valor", entity.ValorTotal);
                try
                {
                    conn.Open();
                    cmd.ExecuteNonQuery();
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }
    }

Controller

public class PedidoController : Controller
    {
        // GET: Pedido
        private GetPedidos respository = new GetPedidos();
        // GET: Pessoa
        public ActionResult Index()
        {
            return View(respository.GetAll());
        }

        // GET: Pessoa/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: Pessoa/Create
        [HttpPost]
        public ActionResult Create(Pedido pedido)
        {
            if (ModelState.IsValid)
            {
                respository.Save(pedido);
                return RedirectToAction("Index");
            }
            else
            {
                return View(pedido);
            }
        }

        // GET: Pessoa/Edit/5
        public ActionResult Edit(int id)
        {
            var pedido = respository.GetById(id);

            if (pedido == null)
            {
                return HttpNotFound();
            }

            return View(pedido);
        }

        // POST: Pessoa/Edit/5
        [HttpPost]
        public ActionResult Edit(Pedido pedido)
        {
            if (ModelState.IsValid)
            {
                respository.Update(pedido);
                return RedirectToAction("Index");
            }
            else
            {
                return View(pedido);
            }
        }

        // POST: Pessoa/Delete/5
        [HttpPost]
        public ActionResult Delete(int id)
        {
            respository.DeleteById(id);
            return Json(respository.GetAll());
        }
    }

Repository

public abstract class RepositoryData<TEntity, TKey>
                where TEntity : class
    {
        protected string StringConnection { get; } = ConfigurationManager.ConnectionStrings["ConnTsL"].ConnectionString;

        public abstract List<TEntity> GetAll();
        public abstract TEntity GetById(TKey id);
        public abstract void Save(TEntity entity);
        public abstract void Update(TEntity entity);
        public abstract void Delete(TEntity entity);
        public abstract void DeleteById(TKey id);
    }

A View

@model IEnumerable<TSL.Models.GetPedidos>

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>

<p>
    @Html.ActionLink("Create New", "Create")
</p>
<table class="table">
    <tr>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
            @Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
        </td>
    </tr>
}

</table>

EDIT1

The Error

The template item inserted in the dictionary is from type'System.Collections.Generic.List1[TSL.Domain.Entities.Pedido]', mas esse dicionário requer um item do tipo 'System.Collections.Generic.List1[TSL.Models.Getpedidos]'.

The view is like this

@model List<TSL.Models.GetPedidos>
  • Post the view code where you "set its type". And the controller code that sends the data to this view.

  • True, I forgot to post the obvious, the main one. Sorry. It’s gone

  • And the view, young man?

  • View expects a list of type GetPedidos if a list of Pedidos

  • I suggest you search the site, because you’re making mistakes that are full of information showing that you can’t do what you’re doing. By not learning to do the right goes into a situation that your codes will always be wrong, until when they work.

1 answer

1

The error describes the problem by itself.

You can simply change the first line of the view to

@model List<TSL.Models.GetPedidos>

Other than that, the types are incompatible. Read the error:

The template item inserted in the dictionary is of the type List[TSL.Domain.Entities.Pedido], but this dictionary requires an item like List[TSL.Models.GetPedidos].

Decide, or you want a list of Pedido or a list of GetPedidos.

  • When I created the view, I made it as a list(List). The error persists, even changing from Ienumerable for List

  • @pnet The error cannot persist. If you are popping an error, it is another.

  • LINQ, I clicked on Action and add View. I added, I chose the type that is List, I selected the Model that is Typed and marked layout and OK. As I decide for the guy?

  • @Now, you want to use a type, don’t you? If you want to use it you know what it is.

Browser other questions tagged

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