user1921145
user1921145

Reputation:

MVC - Get List of values from Database

I'm new in MVC asp.net and I want print a list of data stored in my mdf database (there is already some data) using entity Framework. I'm trying follow the microsoft's mvc tutorial and doing some changes to learn manipulating this. My controller code is:

public ActionResult Index()
{
    var data= storeDB.GenreTable.ToList();
    return View(data);
}

At html code I have:

@model IEnumerable<projectTest.Models.Genre>
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
 }

<ul>
    @foreach (var genre in Model)
    {
        <li>@Html.ActionLink(genre.description, "Browse", new {genre = genre.description})</li>
    }
</ul>

when I go to test I receive

'The model item passed into the dictionary is of type 'System.Collections.Generic.List1[projectTest.genre]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[projectTest.Models.Genre]'

What could be the solution of this? I already tried to change some configurations in my web.config. Many thanks!

Upvotes: 0

Views: 3795

Answers (1)

Tommy
Tommy

Reputation: 39807

The error is very explicit in what the problem is in this instance. You have decorated your view with the following:

@model IEnumerable<projectTest.Models.Genre>

But, you are passing this as your model

storeDB.GenreTable.ToList();

which is a list of projectTest.Genre. In order to make this work, you either need to update your view to accept an IEnumerable of the type you are passing:

@model IEnumerable<projectTest.Genre>

Or, you need to pass the correct view model back to your view, using something like the following (since I don't know what the projectTest.Models.Genre class looks like):

var data= storeDB.GenreTable.Select(x=>new projectTest.Models.Genre{
    name = x.Name, 
    description = x.Description
}).ToList();

Upvotes: 1

Related Questions