0

我需要在 ASP.NET 页面中生成以下内容。最好、最简单的方法是什么?

简化示例。因此,对于自定义属性,我需要将包含索引(i)的字符串传递给控件的属性。我可以从代码隐藏中做到这一点,但如果我可以将它保存在 .aspx 文件中,它会更简单、更容易。

<table>
<% 
    for( var i = 0; i < 10; i++ )
{
%><tr>
    <td>
        <cc1:CustomControl runat="server" CustomProperty="SomeText[<% i %>]"/>
    </td>
</tr>
<% } %>
</table>

本质上,我需要将一个自定义的,而不是预先确定的值传递给 asp.net 控件。

4

3 回答 3

2

这可能不会像您期望的那样工作。相反,添加这样的占位符:

<table>
  <asp:PlaceHolder id="RowPlaceHolder" runat="server" />
</table>

然后在你的代码后面:

for (int i = 0;i<10;i++)
{
   var tr = new HTMLTableRow();
   var td = new HTMLTableCell();
   var Custom = (CustomControl)LoadControl("MyControl.ascx");
   Custom.id="Custom" + i.ToString();
   Custom.CustomProperty = "SomeText[" + i.ToString() + "]";

   td.Controls.Add(Custom);
   tr.Controls.Add(td);
   RowPlaceHolder.Controls.Add(tr);
}

再深入一点,如果数字 10 真的是硬编码的,那么从长远来看,如果您继续手动将 10 个用于控件的条目复制到 aspx 标记中,您会发现事情更容易处理。ASP.Net 网络表单中的动态控件充满了陷阱和陷阱。

如果该数字来自某个合法的数据源,那么您最好实际使用该数据源并将其绑定到像转发器这样的数据控件。

于 2009-07-08T21:28:48.063 回答
0
<%= i %>

应该为你工作。

于 2009-07-08T21:26:42.077 回答
0

您可以使用中继器并使用 Container.ItemIndex,

<asp:Repeater ID="rpt" runat="server">
    <HeaderTemplate>
        <table>
    </HeaderTemplate>
    <ItemTemplate>
        <tr>
            <td> 
                <cc1:CustomControl runat="server" CustomProperty="SomeText[<%# Container.ItemIndex %>]"/>
            </td>
        </tr>
    </ItemTemplate>
    <FooterTemplate>
        </table>
    </FooterTemplate>
</asp:Repeater>
于 2009-07-08T21:36:25.427 回答