Stefan
Stefan

Reputation: 14873

How to bind DbContext from Model to View

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?

Upvotes: 2

Views: 3117

Answers (1)

mfanto
mfanto

Reputation: 14428

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:

public ActionResult Index()
{
    return View("Hello World");
}

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:

@model string

And usage becomes:

<div>@Model</div>

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:

public ActionResult Index()
{
    using (var db = new UsersContext()) 
    {
        var items = db.Items.ToList();

        return View(items);
    }
}

and then in your view:

@model IEnumerable<ItemDB>

and you can use it as:

@foreach (var item in Model)
{
    <div>@item.Title</item>
}

Upvotes: 3

Related Questions