如何像在ASP中一样在WebForms中循环数据.网络MVC?例如,在MVC中,这很简单:
<table>
@foreach (var myItem in g)
{
@<tr><td>@MyItem.title<td></tr>
}
</table>
后面的代码会是什么样子呢?
或者,我可以将MVC项目添加到WebForms应用程序中,以便使用MVC功能吗?
如何像在ASP中一样在WebForms中循环数据.网络MVC?例如,在MVC中,这很简单:
<table>
@foreach (var myItem in g)
{
@<tr><td>@MyItem.title<td></tr>
}
</table>
后面的代码会是什么样子呢?
或者,我可以将MVC项目添加到WebForms应用程序中,以便使用MVC功能吗?
您可以使用类似的MVC类型的方式,使用<% %>
和<%= %>
标记,而不是使用转发器来循环列表.
<table>
<% foreach (var myItem in g) { %>
<tr><td><%= myItem.title %></td></tr>
<% } %>
</table>
只要您正在循环访问的属性可以从aspx/ascx页面访问(例如,声明为受保护的或公共的),您就可以循环访问它.代码隐藏中没有其他代码是必要的.
<% %>
将判断代码,<%= %>
将输出结果.
以下是最基本的例子:
在你的代码隐藏中,在你的类级别声明以下列表:
public List<string> Sites = new List<string> { "StackOverflow", "Super User", "Meta SO" };
这只是一个简单的字符串列表,所以在您的ASPX文件中
<% foreach (var site in Sites) { %> <!-- loop through the list -->
<div>
<%= site %> <!-- write out the name of the site -->
</div>
<% } %> <!--End the for loop -->