locked
"InvalidOperationException" error showing values from model in ASP.NET Core MVC and Entity Framework Core? RRS feed

  • Question

  • User-405684302 posted
    I am trying to show values in table from controller to view using model but it shows an error. I have debugged and checked values are returned OK, but the code shows an error. I don't know where is problem please let me know how can I resolve/fix this issue?

    Here is my code:
    Model:

    public class RoomsStatus
    {
    [Key]

    public int Id { get; set; }
    public DateTime CheckInDateTime { get; set; }
    public DateTime CheckOutDateTime { get; set; }
    public decimal DailyPricePerBed { get; set; }
    public int AmountOfBeds { get; set; }
    public string PriceType { get; set; }
    public bool Paid { get; set; }
    public string Name { get; set; }

    public int RoomNumber { get; set; }
    }
    ApplicationDbConext:

    public class ApplicationDbContext : IdentityDbContext
    {
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
    : base(options)
    {
    }

    public DbSet<RoomsStatus> RSN { get; set; }
    }
    RoomsController:

    //view booking details and rooms status
    public async Task<IActionResult> RoomsStatus(int PartnerID,int BuldingID)
    {
    try
    {
    return this.View("RoomsStatus", await _context.RSN.FromSqlRaw("EXECUTE dbo.GetRoomsStatusByID {0},{1}", PartnerID, BuldingID).ToListAsync());
    }
    catch (Exception e)
    {
    //Logger.LogError(e, "Error while displaying booking.");
    return this.RedirectToAction("Error", "Base");
    }
    }
    RoomStatus view:

    @model IEnumerable<FewoVerwaltung.Models.RoomsStatus>

    <h1>RoomsStatus</h1>

    <table class="table">
    <thead>
    <tr>
    <th>
    Name
    </th>
    </tr>
    </thead>
    <tbody>
    @foreach (var item in Model)
    {
    <tr>
    <td>

    @Html.DisplayFor(modelItem => item.Name)
    </td>
    </tr>
    }
    </tbody>
    </table>
    And this is the error I get:
    Stack InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'System.Collections.Generic.List1[FewoVerwaltung.Models.RoomsStatus]', but this ViewDataDictionary instance requires a model item of type 'FewoVerwaltung.Models.Base.BaseModel'
    Saturday, June 6, 2020 7:33 PM

Answers

  • User1120430333 posted

    I am trying to show values in table from controller to view using model but it shows an error. I have debugged and checked values are returned OK, but the code shows an error. I don't know where is problem please let me know how can I resolve/fix this issue?

    You should be using a viewmodel that is strong typed to the view and not the persistence model used by EF the ORM and persistence framework. You map EF model object to VM object and vice versa to persist data to the database.

    https://www.dotnettricks.com/learn/mvc/understanding-viewmodel-in-aspnet-mvc

    Stack InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'System.Collections.Generic.List1[FewoVerwaltung.Models.RoomsStatus]', but this ViewDataDictionary instance requires a model item of type 'FewoVerwaltung.Models.Base.BaseModel'

    You execute a sproc that came back with a List<T> generic list strong typed  a System.Collections.Generic.List1[FewoVerwaltung.Models.RoomsStatus> and the view wants 'FewoVerwaltung.Models.Base.BaseModel' and they are not the same objects.

    I would say make a VM from the call you made to the sproc, going into a loop on the returned results create the VM from the sproc List<T> results and send the List<T> of the VM into the view. You can use the Linq Addrange() and crate a VM object in a list and send the list of VM(s) inmto the view.

    public AuthorVM GetAll()
            {
                var vm = new AuthorVM();
    
                var dtos = svc.GetAll().ToList();
    
                vm.Authors.AddRange(dtos.Select(dto => new AuthorVM.Author()
                {
                    AuthorID = dto.AuthorId,
                    FirstName = dto.FirstName,
                    LastName = dto.LastName
                }).ToList());
    
                return vm;
    }
    
    =====================================
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    
    namespace PublishingCompany.Models
    {
        public class AuthorVM
        {
            public class Author
            {
                public int AuthorID { get; set; }
    
                [Required(ErrorMessage = "First Name is required")]
                [StringLength(50)]
                public string FirstName { get; set; }
    
                [Required(ErrorMessage = "Last Name is required")]
                [StringLength(50)]
                public string LastName { get; set; }
            }
    
            public List<Author> Authors { get; set; } = new List<Author>();
        }
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, June 6, 2020 8:44 PM

All replies

  • User1120430333 posted

    I am trying to show values in table from controller to view using model but it shows an error. I have debugged and checked values are returned OK, but the code shows an error. I don't know where is problem please let me know how can I resolve/fix this issue?

    You should be using a viewmodel that is strong typed to the view and not the persistence model used by EF the ORM and persistence framework. You map EF model object to VM object and vice versa to persist data to the database.

    https://www.dotnettricks.com/learn/mvc/understanding-viewmodel-in-aspnet-mvc

    Stack InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'System.Collections.Generic.List1[FewoVerwaltung.Models.RoomsStatus]', but this ViewDataDictionary instance requires a model item of type 'FewoVerwaltung.Models.Base.BaseModel'

    You execute a sproc that came back with a List<T> generic list strong typed  a System.Collections.Generic.List1[FewoVerwaltung.Models.RoomsStatus> and the view wants 'FewoVerwaltung.Models.Base.BaseModel' and they are not the same objects.

    I would say make a VM from the call you made to the sproc, going into a loop on the returned results create the VM from the sproc List<T> results and send the List<T> of the VM into the view. You can use the Linq Addrange() and crate a VM object in a list and send the list of VM(s) inmto the view.

    public AuthorVM GetAll()
            {
                var vm = new AuthorVM();
    
                var dtos = svc.GetAll().ToList();
    
                vm.Authors.AddRange(dtos.Select(dto => new AuthorVM.Author()
                {
                    AuthorID = dto.AuthorId,
                    FirstName = dto.FirstName,
                    LastName = dto.LastName
                }).ToList());
    
                return vm;
    }
    
    =====================================
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;
    
    namespace PublishingCompany.Models
    {
        public class AuthorVM
        {
            public class Author
            {
                public int AuthorID { get; set; }
    
                [Required(ErrorMessage = "First Name is required")]
                [StringLength(50)]
                public string FirstName { get; set; }
    
                [Required(ErrorMessage = "Last Name is required")]
                [StringLength(50)]
                public string LastName { get; set; }
            }
    
            public List<Author> Authors { get; set; } = new List<Author>();
        }
    }

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, June 6, 2020 8:44 PM
  • User-405684302 posted
    Hi,
    Thanks for response and guide me. But issue is i want to must used SQL query as you can see i use stored procedure by providing paramaters. This is not issue and i also debuge its working and values are ok and list arereturned. But it show error which i mentioned above. Please let me know how to fix base model. What is base model? I am not using base model in this view but i am using base model in application. Thanks.
    Saturday, June 6, 2020 8:54 PM
  • User1120430333 posted

    Hi,
    Thanks for response and guide me. But issue is i want to must used SQL query as you can see i use stored procedure by providing paramaters. This is not issue and i also debuge its working and values are ok and list arereturned. But it show error which i mentioned above. Please let me know how to fix base model. What is base model? I am not using base model in this view but i am using base model in application. Thanks.

    What is coming out the sproc is a generic list<FewoVerwaltung.Models.RoomsStatusf> that's never going to match  FewoVerwaltung.Models.Base.BaseModel. the view wants.

    The only thing you can do here is use a VM or go into a foreach loop on generic list<FewoVerwaltung.Models.RoomsStatusf> map it over to a List<FewoVerwaltung.Models.Base.BaseMode> an send the list into the view.

    Saturday, June 6, 2020 11:06 PM
  • User-405684302 posted
    Hi,
    Thanks again for response, i am really sorry i disturb you, just let me know my model name is "RoomStatus" not base model. Then why it showing base model?? I need to change in base model as well?? I have create new modelw with name "RoomStatus" which are not inherit witj base model?
    Sunday, June 7, 2020 4:30 AM
  • User-405684302 posted

    Hi, I do all these but still showing same error and i also debug and check values,values are returned OK, 

    Error 

    "InvalidOperationException: The model item passed into the ViewDataDictionary is of type 'FewoVerwaltung.Models.RoomsStatusVM', but this ViewDataDictionary instance requires a model item of type 'FewoVerwaltung.Models.Base.BaseModel'."

    Sunday, June 7, 2020 12:13 PM
  • User1120430333 posted
    So I will assume that you didn't change the view to use the view model, You should pos tdd the code.
    You can't tell a horse object that it's now to be a bird object.
    Sunday, June 7, 2020 1:36 PM
  • User-405684302 posted

    Hi, Thanks my issue is resolved , i have inherit base model and do modification base model

    Sunday, June 7, 2020 5:15 PM