I’m new to MVC and have this simple Problem (I think).
I have a DbContext
public class UsersContext : DbContext
{
public UsersContext() : base("Share_DB") {}
public DbSet<ItemDB> Items { get; set; }
}
which contains a list of items with id and Title:
[Table("Items")]
public class ItemDB
{
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string Title { get; set; }
}
and I want to bind a list with all the itemes in the Database table to the model. However I can’t figure out how to do that.
In the View (cshtml file) I guess I have define which model I have to use ( @model XXX.Models.ItemModel ) then Display it with something like:
<ul>
@foreach (XXX.Models.ItemModel.ItemDB item in @Items)
{
<li>@item.Title</li>
}
</ul>
However it can’t find the @Items property is not found. How do I write this?
The way MVC works is when you return a view in your controller, whatever gets passed to View() ends up as the Model property. In other words:
Will pass the string “Hello World” to your View. Then at the top of your Index.cshtml file, you need to declare the model type:
And usage becomes:
In your case, you just need to pass your list of Items to the view, and tell it to expect the right type of model:
and then in your view:
and you can use it as: