Reading dynamically generated HTML element value in codebehind in ASP.NET
Asked Answered
D

5

6

I have an asp.net page where I have the below markup. Basically this markup is generated from codebehind by reading records from a table and looping through them. For each record in table, there will be a div block.

Basically this form is to read/show settings for a user. The settings entries are stored in a table.

<div id='divContainer' runat='server'>

 <div id='div1' runat='server'>
    <table>
      <tr>
        <th>Name</th>
        <td><input type='text' id='txtName1' value='something' /></td>
      </tr>
       </table>
 </div>
 <div id='div2' runat='server'>
    <table>
      <tr>
        <th>Domain name</th>
        <td><input type='text' id='txtName2' value='something' /></td>
      </tr>
     </table>
 </div>
 <div id='div3' runat='server'>
    <table>
      <tr>
        <th>URL</th>
        <td><input type='text' id='txtName3' value='something' /></td>
      </tr>
      </table>
 </div>
 <div id='div4' runat='server'>
    <table>
      <tr>
        <th>Some other value is enabled ?</th>
        <td><input type='checkbox' id='chk4'  /></td>
      </tr>
      </table>
 </div>

</div>

The id's of each input element will be unique. Now in codebehind I want to read the values of each input element to save the changes user made. How can I read the elements here? Since the mark up is generated in codebehind as a string and appended the the INNER HTML of the external div, I can't read values like we do for a control which we drag and drop in the IDE.

Dacy answered 28/12, 2010 at 13:12 Comment(7)
How are you adding the controls? As strings? As server controls (adding to a Controls collection? Something else?Crake
what happens when you make the controls runat="server"? Can't still reach them?Saphead
You may be interested to know that your table elements are missing their closing tags.Veator
@Veator : My mistake ! Fixed. , Oded : I am creating a string and assigning to the inner HTML property of the external divDacy
Why aren't you using a MS control that would do this for you and save you the headache? There are several, including GridView that are perfect for what you want to do here.Insula
@Shyju: Can't you just keep the input type in DB and dynamically add the controls instead of changing the InnerHTML of a serverside Div?Saphead
Also, PLEASE ACCEPT MORE ANSWERS TO QUESTIONS OR EDIT THE QUESTIONS TO INCLUDE MORE CONTENT.Insula
V
4

If these are being sent back to the page in a standard HTTP POST then you can read the values in the Request.Form NameValueCollection.

Essentially, all of the server controls that become form elements get translated into standard HTML form elements just as you have there, albeit with more markup generated by .NET to help it identify them. Then it automatically maps their values back to the server controls for you on the postback, but the values themselves are still just in a standard HTTP POST, which you can access manually.

(This is also a common method used when posting a form from one ASP .NET application to another.)

Veator answered 28/12, 2010 at 13:20 Comment(7)
Dynamically added elements won't get translated back into server controls tho. So he can't look for txtName3.Text in the serverside code. He'll have to parse that NVC or he'll have to have some other way to rebuild the request data into a form.Insula
@drachenstern: They're not server controls, no. But the values are present in Request.Form and can be pulled out by element name easily enough. As for keeping them persistent on the dynamic page, that's going to take some work. But the basic idea of getting the values on the postback can work just like getting form values in just about any other server-side language.Veator
True, hence my response that it depends on how he's looking to use them. If he expects txtName3.Text then this won't work. I think you and I agree here, I just don't think he understands page lifecycle, or he's not looking to use the ASP.NET engine the way everyone else does. For that matter, I'ld just use a gridview or something similar with command buttons and be done with it. So much easier.Insula
@drachenstern: Pretty much, ya. Though I'd say he's sitting on an opportunity to learn a lot about the nature of his development environment rather than just drag a control onto a form (such as gridview) and have it just work. What he's trying to do isn't far-fetched at all, and is often seen in something like PHP or even in ASP .NET MVC. Nothing wrong with a little manual form manipulation at all.Veator
I agree there. I just don't do it in my apps ;)Insula
@drachenstern: Bah, Microsoft's tools make new developers soft and unable to adapt. In my day we wrote our Perl CGI scripts in vi and we liked it!Veator
lol, oh stop, you're making me blush ;) I wish more devs understood how to telnet into a server to send email, using these piddly HTML clients and all their fancy "UI"s of checking email. Remember the days of connecting to the internet over SLIP connections? Jeeze those were the days. If we could only get devs to understand HTTP Verbs I'ld be happy. "What happens when you POST" vs "What happens when you GET" ... That'ld be nice huh?Insula
L
1

If you want to grab your values for the generated controls you have to do 2 things.

  1. Generate the input controls with a runat='server' tag for each control (otherwise they will not be included in the Request.Forms collection.) This is probably the step your missing.

    <input type='text' id='txtName1' runat='server' value='something' />

  2. Grab your values from the Request.Form collection on postback

    string txtValue1 = Request.Form["txtName1"];

It really should be that easy. I tested this against your code using a DIV as the container and a simple javascript to inject the control string into the innerHTML. If your getting any issues you may have to debug and see if the dynamic control ID has changed due to inserting them into naming container or something.

Leeward answered 28/12, 2010 at 19:25 Comment(0)
S
0

Generally, you'd place those input controls you're creating dynamically (in this case, a TextBox) inside something like a panel control (the container). Then after the user has posted their data, you'd loop that container panel.Controls collection and retrieve each TextBox text.

Be aware that some caveats apply when working with dynamically created controls because ASP is of stateless nature.

This page shows how to implement this:

Adding Dynamic Rows in ASP.Net GridView Control with TextBoxes

Sandor answered 28/12, 2010 at 13:21 Comment(0)
I
0

So the brunt of the story is that when you dynamically add a control after Page_Init then POSTBACK values can not be inserted back into those controls.

CF: http://www.15seconds.com/issue/020102.htm and http://msdn.microsoft.com/en-us/library/ms178472.aspx

Some of the other answers here suggest "oh, add a runat=server to the control" but when you create it in the codebehind, and not in the Page_Init, then that makes ZERO difference.

Let me know if that's not how you're creating the controls or if that's not how you're using them and I'll revise this answer on more details. It really all boils down to how you're trying to access the values.

Insula answered 28/12, 2010 at 13:24 Comment(9)
I am reading the records from a table and looping thru it.Creating a string which has the markup and then assigning to the inner HTML property of the external div.Dacy
No, how are you using them on postback? Are you reading txtName3.Text?Insula
actually it does, whenever you create a control on codebehind, that is serverside for sure. OP doesn't "create control" serverside instead changes the innerHtml of a serverside control..Saphead
@Saphead ~ Your comment makes NO SENSE to me. I'm talking about the asp.net engine automatically populating the data back into the boxes so he can access them by variable name. You're talking about the presentation going to the user. I don't think you've read the links I've referenced, and I don't think you understand the point I'm making. He can't rely on the ASP.NET engine to put his post values back, he's going to have to do what @Veator said.Insula
@drachenstern: OP isn't adding CONTROLS to the page, he is just adding(changing) HTML code. About serverside controls that are dynamically added, you can keep them in session and load them back on POSTBACK (which will help you keep the entered values in them)but this has nothing to do with what OP asks.Saphead
@Saphead ~ How would you load the controls back from the session? I'm talking about WebForms loading values into the txtNameX boxes via the lifecycle. What are you talking about? Are you talking about what @Veator is talking about? He and I understand each other just fine. I'm lost the point you're trying to make here.Insula
Now we start to understand each other too :) wasn't talking about clientside controls like you did, sorry.Saphead
@Saphead ~ Ah-ha! Yay agreement ;) ~ Now to see if the OP understands ANY of the myriad conversations on this page.Insula
@drachenstern He should first understand what he wants to do :)Saphead
C
-1

I didn't test it but I can suggest that:

Add your dynamic controls with runat="server" tag inside another controls with runat="server"(such as panel control). Then you can access them like this:

Textbox t = (Textbox)panel1.controls.findControl("dynamicControlId");
Confiding answered 28/12, 2010 at 13:23 Comment(1)
Dynamically added controls are by definition run on the server to begin with. Oh nevermind, strings are inherently NOT controls. I see your point, but it still wouldn't work.Insula

© 2022 - 2024 — McMap. All rights reserved.