InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'System.Collections.Generic.List`1', but this ViewDataDictionary instance requires a model item of type 'Another Model'.

InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'System.Collections.Generic.List`1', but this ViewDataDictionary instance requires a model item of type 'Another Model'.

Click to Watch Video

An unhandled exception occurred while processing the request.

InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'System.Collections.Generic.List`1', but this ViewDataDictionary instance requires a model item of type 'Another Model'.
 
Problem: This error comes when you want to use two different types of Models on the same razor page. Reasons being that maybe you want to include a ViewComponent on the same page where a List of a different type of Model is being rendered.

Solution:
//In your ViewComponent C# file make sure you pass in a parameter of the type of Model you are expecting to be passed to the ViewComponent Default CSHTML file. For example

public async Task<IViewComponentResult> InvokeAsync(TypeOfClass object)
        {
            return View(object);

        }


//Then from the Razor Page at the Front-End, invoke the ViewComponent and pass the object of type as shown above
<div class="container-fluid col-lg-8 col-md-8">

            @await Component.InvokeAsync("TypeOfClass", new NameSpace.FolderOfYourModels.TypeOfClass{ PropertyName=Model.FirstOrDefault().PropertyName, 
                                                                   PropertyName=Model.FirstOrDefault().PropertyName})
        </div>?

Edit this Article
Was this page helpful?
Yes Yes! this solution to the problem was helpful. No No! this solution to the problem was not helpful.. Leave ErnesTech Feedback.Feedback
If you log in, you will be notified when someone leaves a comment.

Other users would like to know if this solution helped you.

sxsq said:

ddw

Your Session is Ending
Login to Continue

© 2021 - ErnesTech - Privacy