C# 在ASP.NET中动态生成HTML

C# 在ASP.NET中动态生成HTML,c#,asp.net,C#,Asp.net,我很想知道asp.net是否允许我们在.aspx源页面(而不是代码背后)上动态生成HTML内联 为了进行测试,我创建了以下simple.aspx页面 在我的asp.net代码中,我有以下内容: protected List<string> myList = null; protected void Page_Load(object sender, EventArgs e) { if (myList == null) my

我很想知道asp.net是否允许我们在.aspx源页面(而不是代码背后)上动态生成HTML内联

为了进行测试,我创建了以下simple.aspx页面

在我的asp.net代码中,我有以下内容:

    protected List<string> myList = null;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (myList == null)
            myList = new List<string>();

        myList.Add("One String");
        myList.Add("Two String");
        myList.Add("Three String");
        myList.Add("Four String");

        this.Repeater1.DataSource = myList;
        this.Repeater1.DataBind();
    }
protectedlist myList=null;
受保护的无效页面加载(对象发送方、事件参数e)
{
if(myList==null)
myList=新列表();
添加(“一个字符串”);
添加(“两个字符串”);
添加(“三个字符串”);
添加(“四个字符串”);
this.Repeater1.DataSource=myList;
this.Repeater1.DataBind();
}
在相应的源页面上,我有:

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <ol>
        <asp:Repeater ID="Repeater1" runat="server">
            <ItemTemplate>
                <li>
                    <%# DataBinder.GetDataItem(myList) %>
                </li>
            </ItemTemplate>
        </asp:Repeater>
    </ol>
</body>
</html>

  • 生成的.aspx页面是:

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head><title>
    
    </title></head>
    <body>
        <ol>
    
                    <li></li>
    
                    <li></li>
    
                    <li></li>
    
                    <li></li>
    
        </ol>
    </body>
    </html>
    
    
    
  • 请注意,Repeater控件实际上创建了四个列表项。然而,myList列表的内容(一个字符串、两个字符串等)并未随车提供

    我需要做什么来计算myList列表并在列表项标记中获取其值?顺便说一句,我并不关心如何具体使用转发器控件,因此,如果有一个解决方案不包括转发器控件,我可以接受

    注意:我知道我可以将“myList”泛型列表绑定到asp:BulletedList并获得相同的结果。我对动态创建源页面的HTML内联更感兴趣。

    使用以下代码:

    <asp:Repeater ID="Repeater1" runat="server">
        <ItemTemplate>
             <li>
                <%# Container.DataItem %>
             </li>
        </ItemTemplate>
    </asp:Repeater>
    
    
    
  • 如果需要将源与具有属性的对象列表绑定,请尝试使用:

    <asp:Repeater ID="Repeater1" runat="server">
        <ItemTemplate>
             <li>
                <%# Eval("PropertyName") %>
                or
                <%# Eval("PropertyName","DataFormat") %>
             </li>
        </ItemTemplate>
    </asp:Repeater>