[SOLVED] InvalidOperationException: The model item passed into the ViewDataDictionary

Issue

There are many questions around this topic I know but I tried different things and couldn’t solve. So my list return code is this, this is QuestionsController, model is Question

public async Task<IActionResult> Index()
{
     return View(await _context.Question.ToListAsync());
}

This is my cshtml and model tag

@model IEnumerable<SocialLearningCommunity.Models.Question>

Error

InvalidOperationException: The model item passed into the
ViewDataDictionary is of type
‘System.Collections.Generic.List`1[SocialLearningCommunity.Models.Question]’,
but this ViewDataDictionary instance requires a model item of type
‘SocialLearningCommunity.Models.User’.

Data class

public DbSet<User> User { get; set; }
public DbSet<Question> Question { get; set; }

Thanks.

Solution

your index view has this line of code

@model SocialLearningCommunity.Models.User

but you are trying to send to the view from the controller action

List <SocialLearningCommunity.Models.Question>

you have to decide which of models you have to use. Or you can have question model in Question view, not in Index one. Or you have a partial view with User model.

Answered By – Serge

Answer Checked By – Katrina (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *