Please Login to Continue

Free Software Development Articles.Email List

Advertise Here

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'.

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>?
Technology published
Buy Me Coffee

Was this page helpful?

Yes Yes! this solution to the problem was helpful. No No! this solution to the problem was not helpful..



© 2020 - ErnesTech - Privacy