Search code examples
c#asp.netasp.net-mvcasp.net-mvc-viewmodel

ASP.NET MVC 5 The model item passed into the dictionary is of type 'Name.Models.IndexViewModel', but this dictionary requires a model item of type


An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack trace:

InvalidOperationException: The model item passed into the dictionary is of type 'Name.Models.IndexViewModel', but this dictionary requires a model item of type 'Name.Models.TwoViewModel'.

I needed two different view models for this view:

public class TwoViewModel
{
    public IEnumerable<Name.Models.Project> Model1 { get; set; }
    public IndexViewModel Model2 { get; set; }
}

EDIT:

I think I have found where the problems come from, the ManageController:

public async Task<ActionResult> Index(ManageMessageId? message)
{
    var userId = User.Identity.GetUserId();
    var userEmail = User.Identity.Name;
    var user = UserManager.FindById(userId);
    var model = new IndexViewModel
    {              
        Email = user.Email,
        FirstName = user.FirstName,
        LastName = user.LastName,
        City = user.City,            
    };    
    return View(model);
}

I have tried changing the ViewModel of the model, trying things like

var model = new TwoViewModel
{
    Model2.Email = user.Email,
    Model2.FirstName = uesr.FirstName,
    Model2.LastName = user.LastName,
    Model2.City = user.City,                       
};             
return View(model);

And intellisense does recognize the Model2 but not the .Email part. I think a nesting would be the case?

I've tried this approach:

var model = new TwoViewModel
{
    Model2 = new IndexViewModel
    {
        Email = user.Email,
        FirstName = user.FirstName,
        LastName = user.LastName,
        City = user.City,
    }
};    
return View(model);

But then another thing gives an

Object reference not set to an instance of an object.

error.

@foreach (var item in Model.Model1)
{
    <tr>
        <td>@Html.DisplayFor(modelItem => item.Title)</td>
        ....
    </tr>
}

This @foreach (var item in Model.Model1) line is the cause of the problem. Now the syntax is good. I have this same line that will retrieve everything from the first model (IEnumerable<Name.Models.Project>) with no problems. I don't know how to deal with this error

EDIT: the solution was that I had to initialize Model1 inside the model of type TwoViewModel inside the ManageController. This fixed my error


Solution

  • The thing causing the problem was that the Model 1 was not initialized and so it was a NULL.

    The solution was that I had to initialize Model1 inside the model of type TwoViewModel inside the ManageController. This fixed my error