2

I want to do something like the following in an asp.net web form but get a Invalid Token error message:

<ul>
    <%foreach (var item in Items) {%>
    <li>
      <asp:TextBox ID="<%= item.Id  %>" runat="server" />
    </li>
    <%} %>
</ul>

What alternative methods are there to achieve the desired result?

2 Answers 2

6

Server side controls (i.e. those with runat="server") have to have IDs set at compile time (because the ID is used to name the member field representing the control).

Either:

  • Use some form of repeater control (i.e. create a collection of controls) and data binding to populate.
  • create HTML (i.e. not server side controls) directly.

In ASP.NET the former is usual, with ASP.NET MVC the latter (via HTML Helpers) is usual.

Sign up to request clarification or add additional context in comments.

2 Comments

By creating HTML directly can i get the control on a postback? Or do i need to specify the ID attribute?
@Akk: you can access the value from Request.Form of any input element, but there will be no ASP.NET control.
1

Give a try to following approach:-

    foreach (Item item in items) 
    {
       TextBox txtBox=new TextBox();
       txtBox.ID=item.ID;
       placeHolder.Controls.Add(txtBox);
    }

Also make sure you dont have any invalid character like ("-"), it can create problem for you sometimes.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.