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?
In WebForm you can use Repeater control:
In code behind:
You can use a
Repeater
with any sort of validDataSource
(SqlDataSource
,EntityDataSource
,ObjectDataSource
) object:....
...
Rather than use a repeater, you can just loop through the list in a similar MVC type way using the
<% %>
and<%= %>
tags.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:
That's just a simple list of strings, so then in your aspx file