Retrieving and displaying multiple records using Entity Framework
The next stage is for us to show a list of the blog titles from our database. Each title should link to a page which will display the entire blog entry.
-
Create a new web form called default.aspx (this will be the home page and provide a list of all the blog entries)
-
Add an appropriate title and h1 to the page (e.g.
My Blog)
-
Add a repeater to the page, and set its ID to
rptrBlogPosts
-
Within code view the repeater add a header template, an
item template and a footer template. Your repeater should look
something like this:
<asp:Repeater ID="rptrBlogPosts" runat="server">
<HeaderTemplate></HeaderTemplate>
<ItemTemplate></ItemTemplate>
<FooterTemplate></FooterTemplate>
</asp:Repeater >
-
Within the header template add an opening
<ul>
tag, and place the closing <ul>
tag in the footer template
-
The item template part of the repeater 'repeats' according the the number of items in the datasource that the repeater is bound to. We will be binding it to a list of our blog posts
-
We are going to add a list item
<li>
to our item template, and place a hyperlink inside it. The hyperlink will use two values from each blog post - the title and the Id. The Id
will be used to create a unique link to page which will display the blog post in full.
-
Add the following line of code inside the ItemTemplate
tags:
<li>
<a href="<%# Eval("Id", "ViewBlogEntry.aspx?Id={0}") %>">
<%#Eval("Title") %>
</a>
</li>
-
The remaining thing to do is to 'bind' the data to the
repeater.
-
Open the default.aspx.cs file and add the following code
within the braces for the Page_Load method:
var db = new DatabaseEntities();
var blogEntries = db.BlogEntries.ToList();
rptrBlogPosts.DataSource = blogEntries.OrderBy(p => p.DateTime);
rptrBlogPosts.DataBind();
-
This code creates a new instance of our database entities and
then sets the datasource of the repeater to use the blog entries
table of the database, ordered by the date of the blog entry.
Once the datasource has been set, it has to be bound to the
repeater.
-
Assuming you added some blog entries in the previous set,
view the page to see a list of blog entries. We have not yet
created a page to view the Blog Entry in full, so the hyperlink
will link to a non existent page.