I have the following requirement for creating a user profile in my application:
User should be able to enter multiple phone numbers/email addresses in his profile.
The screen looks somewhat like this:
– By default, on page load a single textbox for phone and email are shown.
– User can click a “+” button to add additional numbers/addresses.
– On clicking the “+” button we need to add another textbox just below the first one. User can add as many numbers/addresses as he wants. On submit, the server should collect all numbers/emails and save it in DB.
I tried using the Repeater control to do this. On page_load I bind the repeater to a “new arraylist” object of size 1. So, this renders fine – user sees a single textbox with no value in it.
When he clicks the “+” button, I ideally want to use javascript to create more textboxes with similar mark-up as the first.
My questions are these:
- Can I render the new textboxes anyway using js? I notice that the HTML rendered by the repeater control is somewhat complex (names/ids) etc. and it might not be possible to correctly create those controls on client-side.
- If there is a way to do #1, will the server understand that these additional inputs are items in the repeater control? Say, I want to get all the phone numbers that the user entered by iterating over Repeater.DataItems.
- Conceptually, is my approach correct or is it wrong to use the Repeater for this? Would you suggest any other approach that might handle this requirement?
Coming from a Struts/JSP background, I am still struggling to get a grip on the .NET way of doing things – so any help would be appreciated.
The repeater control may be a bit of overkill for what you’re trying to accomplish. It is mainly meant as a databound control for presenting rows of data.
What you can do is to dynamically create the boxes as part of the
Page_Loadevent (C#):TestInput.aspx :
TestInput.aspx.cs:
I ended up using a
PlaceHolderto dynamically add the text boxes and aHiddenFieldto flag when anotherTextBoxneeded to be added. Since the IDs were matching, it maintains the ViewState of the controls during each postback.