locked
Cannot convert type 'System.Collections.Generic.KeyValuePair<string,object>' to 'Alqadhi.Data.Models.Employee' RRS feed

  • Question

  • User391212375 posted

    i have tow models in one View 

    See Error Message

    Customer Model :

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.ComponentModel.DataAnnotations;
    namespace Alqadhi.Data.Models
    {
        public class Customer
        {
            [Key]
            public int CustomerID { set; get; }
            public string CustomerName { set; get; }
        }
    }

    Employee Model :

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;
    using System.ComponentModel.DataAnnotations;
    namespace Alqadhi.Data.Models
    {
        public class Employee
        {
            [Key]
            public int EmployeeID { set; get; }
            public string EmployeeName { set; get; }
        }
    }
    

    Controller :

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using Alqadhi.Data.Models;
    using System.Dynamic;
    namespace Alqadhi.Controllers
    {
        public class HomeController : Controller
        {
            Alqadhi.Data.EFDbContext db =new Alqadhi.Data.EFDbContext();
    
            public ActionResult Index()
            {
                dynamic model = new ExpandoObject();
                model.Customers = GetCustomers();
                model.Employees = GetEmployees();
                return View(model);
            }
            private static List<Customer> GetCustomers()
            {
                List<Customer> customers = new List<Customer>();
                return customers;
            }
            private static List<Employee> GetEmployees()
            {
                List<Employee> Employies = new List<Employee>();
                return Employies;
            }
         
        }
    }

    View

    @using Alqadhi.Data.Models;
    @model dynamic
    @{
        ViewBag.Title = "Home Page";
    }
    
    <!-- Employies -->
    <table class="table">
        <thead>
            <tr>
                <th scope="col">Employee ID</th>
                <th scope="col">Employee Name</th>
            </tr>
        </thead>
        <tbody>
    
    @if (Model !=null)
    {
        foreach (Employee Emp in Model)
            {
              <tr>
                <th scope="row">@Emp.EmployeeID</th>
                <td>@Emp.EmployeeName</td>
            </tr> 
            }
      }
        </tbody>
    </table>
    
    
    <!-- Customers -->
    <table class="table">
        <thead>
            <tr>
                <th scope="col">Customer ID</th>
                <th scope="col">Customer Name</th>
            </tr>
        </thead>
        <tbody>
    
            @if (Model != null)
            {
                foreach (Customer Cust in Model)
                {
                    <tr>
                        <th scope="row">@Cust.CustomerID</th>
                        <td>@Cust.CustomerName</td>
                    </tr>
                }
            }
    
    
        </tbody>
    </table>

    after run the project i see this error 

    Server Error in '/' Application.


    Cannot convert type 'System.Collections.Generic.KeyValuePair<string,object>' to 'Alqadhi.Data.Models.Employee'

    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: Cannot convert type 'System.Collections.Generic.KeyValuePair<string,object>' to 'Alqadhi.Data.Models.Employee'

    Source Error:

    Line 17: @if (Model !=null)
    Line 18: {
    Line 19:     foreach (Employee Emp in Model)
    Line 20:         {
    Line 21:           <tr>


    Source File: c:\Source Code\Impact\Web Site\Alqadhi\Alqadhi\Views\Home\Index.cshtml    Line: 19

    Tuesday, October 8, 2019 10:40 PM

All replies

  • User-17257777 posted

    Hi alqadhi99,

    ExpandoObject allows you to store multiple objects in the form <Key, Value>, so you need to get the corresponding Value through Key. You can change your codes like below:

    View:

    <table class="table">
        <thead>
            <tr>
                <th scope="col">Employee ID</th>
                <th scope="col">Employee Name</th>
            </tr>
        </thead>
        <tbody>
    
            @if (Model != null)
            {
                foreach (Employee Emp in Model.Employees)
                {
                    <tr>
                        <th scope="row">@Emp.EmployeeID</th>
                        <td>@Emp.EmployeeName</td>
                    </tr>
                }
            }
        </tbody>
    </table>
    
    
    <!-- Customers -->
    <table class="table">
        <thead>
            <tr>
                <th scope="col">Customer ID</th>
                <th scope="col">Customer Name</th>
            </tr>
        </thead>
        <tbody>
    
            @if (Model != null)
            {
                foreach (Customer Cust in Model.Customers)
                {
                    <tr>
                        <th scope="row">@Cust.CustomerID</th>
                        <td>@Cust.CustomerName</td>
                    </tr>
                }
            }
    
    
        </tbody>
    </table>
    

    Test Result:

    Best Regards,

    Jiadong Meng

    Wednesday, October 9, 2019 7:39 AM
  • User391212375 posted

    I test the code and it didn't work
    Is it possible to test the code in your computer?
    I am a beginner programmer and I need help with

    best way to add multi Model on one View 

    Wednesday, October 9, 2019 8:39 AM
  • User391212375 posted
    @using Alqadhi.Data.Models;
    @model dynamic
    @{
        ViewBag.Title = "Home Page";
    }
    <table class="table">
        <thead>
            <tr>
                <th scope="col">Employee ID</th>
                <th scope="col">Employee Name</th>
            </tr>
        </thead>
        <tbody>
    
            @if (Model != null)
            {
                foreach (Employee Emp in Model.Employees)
                {
                    <tr>
                        <th scope="row">@Emp.EmployeeID</th>
                        <td>@Emp.EmployeeName</td>
                    </tr>
                }
            }
        </tbody>
    </table>
    
    
    <!-- Customers -->
    <table class="table">
        <thead>
            <tr>
                <th scope="col">Customer ID</th>
                <th scope="col">Customer Name</th>
            </tr>
        </thead>
        <tbody>
    
            @if (Model != null)
            {
                foreach (Customer Cust in Model.Customers)
                {
                    <tr>
                        <th scope="row">@Cust.CustomerID</th>
                        <td>@Cust.CustomerName</td>
                    </tr>
                }
            }
    
    
        </tbody>
    </table>

    Cannot convert type 'System.Collections.Generic.KeyValuePair <string, object>' to 'Alqadhi.Data.Models.Employee'

    Wednesday, October 9, 2019 8:42 AM
  • User1120430333 posted

    You should learn how to use a viewmodel, not sending the EF model into the view.

    https://weblogs.asp.net/dotnetstories/viewmodels

    Below, you see a viewmodel StudentViewModel that contains another viewmodel EnrollandCourseViewModel with both viewmodels being used in the view

    namespace MVC.Models
    {
        public class StudentViewModels
        {
            public List<Student> Students { get; set; }
    
            public class Student
            {
                public Int32 StudentID { get; set; }
    
                [Required(ErrorMessage = "Last Name is required")]
                [StringLength(50)]
                public string LastName { get; set; }
    
                [Required(ErrorMessage = "First Name is required")]
                [StringLength(50)]
                public string FirstName { get; set; }
    
                [Required(ErrorMessage = "Enrollment Date is required")]
                [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM-dd-yyyy}")]
                public DateTime? EnrollmentDate { get; set; }
                public virtual ICollection<EnrollandCourseViewModel.EnrollandCourse> EnrollsandCourses { get; set; }
            }
        }
    }
    using System;
    using System.Collections.Generic;
    
    namespace MVC.Models
    {
        public class EnrollandCourseViewModel
        {
            public class EnrollandCourse
            {
                public decimal? Grade { get; set; }
                public string Title { get; set; }
                public Int32? Credits { get; set; }
            }
        }
    }
    @model MVC.Models.StudentViewModels.Student
    
    @{
        Layout = null;
    }
    
    <!DOCTYPE html>
    
    <html>
    <head>
        <title>Details</title>
     </head>
    <body>
    <h1>Student Details</h1>
        
    @Html.Label("First Name:") @Html.DisplayFor(m => m.FirstName) <br/>
    @Html.Label("Last Name:") @Html.DisplayFor(m => m.LastName) <br/>
    @Html.Label("Enrollment Date:") @Html.DisplayFor(m => m.EnrollmentDate) <br/>
        
    <br/><br/><br/>
        
    <table class="table">
            <tr>
                <th>
                    Course Title
                </th>
                <th>
                    Grade
                </th>
                <th>
                    Credits
                </th>
            </tr>
    
            @foreach (var item in Model.EnrollsandCourses)
            {
                <tr>
                    <td>
                        @Html.DisplayFor(modelItem => item.Title)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Grade)
                    </td>
                    <td>
                        @Html.DisplayFor(modelItem => item.Credits)
                    </td>
                </tr>
            }
        </table>
    
    
    </body>
    </html>   
        
        
    
    

    Wednesday, October 9, 2019 9:28 AM