How to loop through data in WebForms like in MVC

asp.netasp.net MvcWebforms

asp.net Problem Overview


How do I loop through data in WebForms like I do in ASP.NET MVC? For instance, in MVC, this is as simple as:

<table>
    @foreach (var myItem in g)
    { 
        @<tr><td>@MyItem.title<td></tr>
    }
</table>

What would the code behind look like?

Or, can I add an MVC project to a WebForms application so that I can use MVC functionality, instead?

asp.net Solutions


Solution 1 - asp.net

Rather than use a repeater, you can just loop through the list in a similar MVC type way using the <% %> and <%= %> tags.

<table>
  <% foreach (var myItem in g) { %>
    <tr><td><%= myItem.title %></td></tr>
  <% } %>
</table>

As long as the property you're looping through is acessible from the aspx/ascx page (e.g. declared as protected or public) you can loop through it. There is no other code in the code behind necessary.

<% %> will evaluate the code and <%= %> will output the result.

Here is the most basic example:

Declare this list at your class level in your code behind:

public List<string> Sites = new List<string> { "StackOverflow", "Super User", "Meta SO" };

That's just a simple list of strings, so then in your aspx file

<% foreach (var site in Sites) { %> <!-- loop through the list -->
  <div>
    <%= site %> <!-- write out the name of the site -->
  </div>
<% } %> <!--End the for loop -->

Solution 2 - asp.net

In WebForm you can use Repeater control:

<asp:Repeater id="cdcatalog" runat="server">
   <ItemTemplate>
       <td><%# Eval("title")%></td>
   </ItemTemplate>
</asp:Repeater>

In code behind:

cdcatalog.DataSource = yourData;
cdcatalog.DataBind();

Solution 3 - asp.net

You can use a Repeater with any sort of valid DataSource (SqlDataSource, EntityDataSource, ObjectDataSource) object:

  1. Define the DataSource

  2. Reference the DataSource in your Reperater

....

 <asp:Repeater id="someRep" runat="server" DataSourceID="YourDataSource">
       <ItemTemplate>
          <tr>
                <td><%# Eval("PropertyName") %></td> 
          </tr>
    </ItemTemplate>
    </asp:Repeater>

...

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser1477388View Question on Stackoverflow
Solution 1 - asp.netBrandonView Answer on Stackoverflow
Solution 2 - asp.netphnkhaView Answer on Stackoverflow
Solution 3 - asp.netMithrandirView Answer on Stackoverflow