I'm new to C# .NET. I would like to ask how this works... What I want is just to show an age selection from 1 to 100.
Inside the .aspx
file I put this code, I used data binding for the variable listAge
.
<asp:DropDownList ID="AgeDropDown" runat="server">
<%# listAge %>
</asp:DropDownList>
Here's the code-behind for it:
protected void Page_Load(object sender, EventArgs e)
{
for (int i = 1; i < 101; i++)
{
string listAge;
listAge = "<asp:ListItem>"+ i +"</asp:ListItem>";
}
}
The error shown inside the .aspx
is:
Er开发者_开发百科ror Creating Control:
AgeDropDown
- Code blocks are not supported in this context.
Because of the variable listAge
?
Thank you for the help!
Drop the <% %> section in .aspx and in code behind you should do something like this:
protected void Page_Load(object sender, EventArgs e)
{
AgeDropDown.Items.Clear();
for (int i = 1; i < 101; i++)
{
AgeDropDown.Items.Add(new ListItem(i.ToString(),i.ToString()));
}
}
From another point of view there are several flaws in your code:
- You are generating ASP.NET tags in code behind. ASP tags are processed on the server and are rendered into html tags. You were practically inserting a tag in html, which browsers will render as simple text since it's not a valid HTML tag.
- You were creating a new listAge variable on each iteration of the for loop. Even if the code would work it would display just the last item
You could use the server version of AgeDropDown
.
ListItem li;
for (int i = 1; i < 101; i++)
{
li = new ListItem(i.ToString(), i.ToString());
AgeDropDown.Items.Add(li);
}
Is this in asp.net or MVC?
Probably
... <%# listAge %>
should be
... <%= listAge %>
精彩评论