I have the following set up for my aspx page called "Default":
public partial class _Default : Page
{
IProjectRepository projectRepository = new SPProjectRepository();
protected void Page_Load(object sender, EventArgs e)
{
ViewModel = new HomeViewModel()
{
Projects = projectRepository.GetProjects
};
}
public HomeViewModel ViewModel { get; set; }
}
On the aspx page, I have the following which works great:
<table>
<thead>
<tr>
<th>Title</th>
</tr>
</thead>
<tbody>
<% foreach( var project in ViewModel.Projects ) { %>
<tr>
<td><%:project.Title%></td>
</tr>
<% } %>
</tbody>
</table>
For learning purposes I wanted to know how I would achieve this with a repeater...
How do I go about using the repeater much in the same way I have written out direct html code with a foreach loop?
I am not sure why you want to skip the traditional DataSource
approach. But if you are using ASP.NET 4.5
then you can use the SelectMethod
(introduced in 4.5 version). Advantage of using this is you can define the Type
by which your repeater control will bind and in templates you will get intellisense support.
Here is a simple example:-
Suppose you have Customer type:-
public class Customer
{
public int Id { get; set; }
public string Name { get; set; }
}
And if you want a list of customers to Repeater control then you can simply define a method and assign it to repeater control. No extra code like Datasource
, DataBind
required.
public IEnumerable rptCustomer_GetData()
{
return new List<Customer>
{
new Customer { Id =1, Name = "xx" },
new Customer { Id =2, Name = "yy" }
};
}
And in repeater just provide that method name:-
<asp:Repeater ID="rptCustomer" runat="server" SelectMethod="rptCustomer_GetData"
ItemType="Customer">
<ItemTemplate>
<asp:Label ID="lblId" runat="server" Text='<%# Item.Id %>'></asp:Label>
<asp:Label ID="lblName" runat="server" Text='<%# Item.Name %>'></asp:Label>
</ItemTemplate>
</asp:Repeater>
Traditional Data Source Approach:-
In Page Load
Simply set the Data Source:-
rptCustomer.DataSource = projectRepository.GetProjects;
rptCustomer.DataBind();
And in mark-up simply use ASP.NET data binding Code nuggets like this:-
<asp:Label ID="lblId" runat="server" Text='<%# Id %>'>