Error sending Controller object to View

Asked

Viewed 27 times

0

I am creating a small project in Asp.net MVC 5 to train and I am having problems passing a Controller object to the View, is showing some error related to the Where<> method of the LINQ library.

Error:

"The model item inserted in the dictionary is of type'System.Linq.Enumerable+Wherelistiterator`1[Project01.Models.Usuario]', but this dictionary requires an item of type 'Project.Models.Usuario''. "

Action that sends the object to the View:

private static int userId;

public ActionResult Perfil()
        {
            if (Session["UserEmail"] != null)
            {
                return View(AllUsers.Where(x => x.UsuarioId == userId));
            }
            else
            {
                return RedirectToAction("Default", "Home");
            }
        }

Object Reference in View:

@model Projeto01.Models.Usuario

NOTE: Remembering that the project does not use Entityframework.

If you need any more information just ask.

  • Look at the link that was answered on this question https://stackoverflow.com/questions/40373595/the-model-item-passed-into-the-dictionary-is-type-but-this-dictionary-requ/47357343#47357343

1 answer

1


The method where() returns a IEnumerable<T>, that is, a collection of objects of a particular type, in your case, a IEnumerable<Usuario>.

The problem there is that your view expects an object of the type Usuario and you are returning a list of them and how the method View() accepts an object, it passes and the alert will be generated only during execution.

For the correct functioning you must do as follows:

return View(AllUsers.FirstOrDefault(x => x.UsuarioId == userId));.

The method FirstOrDefault() will return the first item in the collection that meets the specified condition.

  • Thank you very much. I was already getting worried thinking that had not been clear enough, the staff was giving dislike, without leaving any comment.

Browser other questions tagged

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