I was interested to know whether or not asp.net is allows us to dynamically generate HTML inline on the .aspx Source page (not the code-behind).
For testing I created the following simple .aspx page...
In my asp.net code-behind I have the following:
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();
}
On the corresponding Source page I have:
<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:Rep开发者_C百科eater>
</ol>
</body>
</html>
The resultant .aspx page is:
<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>
Notice that the Repeater control did in fact create the four list items. However, the contents (One String, Two String, etc) of the myList list did not come along for the ride.
What do I need to do to evaluate the myList list and get its values inside the list item tags? By the way, I'm not concerned with how to use the Repeater control specifically, so if there is a solution to this problem that does not include the Repeater control, I'm fine with that.
Note: I'm aware that I can bind the "myList" generic list to an asp:BulletedList and get the same result. I am more interested in dynamically creating HTML inline of the Source page.
Use this code:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<li>
<%# Container.DataItem %>
</li>
</ItemTemplate>
</asp:Repeater>
If you need to bind source with list of objects with properties, try to use:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate>
<li>
<%# Eval("PropertyName") %>
or
<%# Eval("PropertyName","DataFormat") %>
</li>
</ItemTemplate>
</asp:Repeater>
精彩评论