asp.net: (c# client-side) how to access html element created after page loads?

user1358261 picture user1358261 · May 14, 2012 · Viewed 9.5k times · Source

Imagine this,

Step 1: ASPX Page Loads.
Step 2: Button fires a script that creates a html element (div, span, etc) with an id or class tag, including runat server attribute.

and my problem is,

Final Step: From my C# file, how to access that element and get it's inner html, so I can save it to a string?

PS: i'll use that string to save it in my mssql database.

Answer

bgolson picture bgolson · May 14, 2012

You cannot create a "real" runat=server element/control without doing a full postback to the server.

The best approach may be to write some script that stores the innerHTML into an ASP.Net hidden field right before you submit the page. You can then access the value of this hidden field to grab the data.

If you're wanting to dynamically create multiple objects, you'll need to use standard html hidden input fields instead, since you can't create asp.net server controls via javascript.

<input type="hidden" name="fieldData_1" value="control 1 html content">
<input type="hidden" name="fieldData_2" value="control 2 html content">

You'll then be able to access these hidden fields from the Request.Form object:

Request.Form["fieldData_1"]

Knowing this, you can now iterate over the form data and process all of your dynamic fields

foreach (string fieldData in Request.Form)
{
    if(fieldData.Contains("fieldData_"){
        //process the data for each field
    }
}

It is also possible to avoid using hidden fields all together and just pass your data to the server directly using the __doPostback('', '') method. This could be implemented in many different ways, so I'll just refer you to http://dopostback.net to read up on how the method works.