简体   繁体   中英

Create a Dynamic List using Entity Framework in MVC Razor

I would like to make a list populate with vehicle makes using a stored procedure and Entity Framework but when it I get the following error:

The model item passed into the dictionary is of type 'System.Collections.Generic.List 1[System.String]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable 1[VehicleInfo.Models.tblVehicle]'.

Model

public partial class tblVehicle 
    {   
        public string BrandName{ get; set; }
    }

Controller

public ActionResult Index() 
    {
       VehicleDBContext db = new VehicleDBContext();

       var brandnames = db.prcGetMakes().ToList();

       return View(brandnames);
    }

View

@model IEnumerable<VehicleInfo.Models.tblVehicle>

<ul id="Makes">
   @foreach (var item in Model)
   {
      <li>@item.BrandName.Distinct()</li>
   }
</ul>

Stored Procedure

CREATE PROCEDURE [dbo].[prcGetMakes] 

AS
BEGIN

    SET NOCOUNT ON;

    SELECT DISTINCT
        UPPER(BrandName) BrandName
    FROM
        tblVehicle
    ORDER BY
        BrandName
END

There must be something amazingly obvious that I am missing but I can't seem to work it out.

Please Help!

From the error message, It looks like the expression db.prcGetMakes().ToList() in your action method returns a list of strings and you are passing that to the view. But your view is strongly typed to a list of tblVehicle objects, Hence getting the error message about the type mismatch.

Solution is to make both types match. You may update your view to be strongly typed list of string type

@model IEnumerable<string>

<ul id="Makes">
   @foreach (var item in Model)
   {
      <li>@item</li>
   }
</ul>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM