use*_*388 46 asp.net asp.net-mvc webforms
如何像在ASP.NET MVC中那样遍历WebForms中的数据?例如,在MVC中,这很简单:
<table>
@foreach (var myItem in g)
{
@<tr><td>@MyItem.title<td></tr>
}
</table>
Run Code Online (Sandbox Code Playgroud)
在WebForms中执行此操作最简单,最简单的方法是什么?背后的代码会是什么样的?
或者,我可以将MVC项目添加到webforms应用程序,以便我可以使用MVC功能吗?
谢谢.
Bra*_*don 74
您可以使用<% %>和<%= %>标签以类似的MVC类型方式循环遍历列表,而不是使用转发器.
<table>
<% foreach (var myItem in g) { %>
<tr><td><%= myItem.title %></td></tr>
<% } %>
</table>
Run Code Online (Sandbox Code Playgroud)
只要您循环访问的属性可以从aspx/ascx页面访问(例如声明为protected或public),您就可以遍历它.代码中没有其他必要的代码.
<% %>将评估代码并<%= %>输出结果.
这是最基本的例子:
在代码后面的类级别声明此列表:
public List<string> Sites = new List<string> { "StackOverflow", "Super User", "Meta SO" };
Run Code Online (Sandbox Code Playgroud)
这只是一个简单的字符串列表,所以在你的aspx文件中
<% foreach (var site in Sites) { %> <!-- loop through the list -->
<div>
<%= site %> <!-- write out the name of the site -->
</div>
<% } %> <!--End the for loop -->
Run Code Online (Sandbox Code Playgroud)
phn*_*kha 11
在WebForm中,您可以使用Repeater控件:
<asp:Repeater id="cdcatalog" runat="server">
<ItemTemplate>
<td><%# Eval("title")%></td>
</ItemTemplate>
</asp:Repeater>
Run Code Online (Sandbox Code Playgroud)
代码背后:
cdcatalog.DataSource = yourData;
cdcatalog.DataBind();
Run Code Online (Sandbox Code Playgroud)