Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to loop through data in WebForms like in MVC

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?

like image 724
user1477388 Avatar asked Feb 06 '13 15:02

user1477388


People also ask

Is MVC faster than web forms?

Show activity on this post. My completely unscientific opinion: Yes; ASP.NET MVC is faster than web forms. ASP.NET MVC gives screen pops on the order of 1 to 2 seconds. Web forms is more like 3 to 5 seconds.

Can I use webform in MVC?

Luckily, the answer is yes. Combining ASP.NET Webforms and ASP.NET MVC in one application is possible—in fact, it is quite easy.

What is foreach loop in MVC?

Generally, the loops in asp.net mvc razor view will work same as other programming languages. We can define the loop inside or outside the code block in razor, and we can use the same foreach looping concept to assign value to define the condition.


2 Answers

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 --> 
like image 166
Brandon Avatar answered Sep 24 '22 01:09

Brandon


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(); 
like image 45
phnkha Avatar answered Sep 24 '22 01:09

phnkha