Question

I am using asp.net 4.0.

Now I want to create some content in the client side using javascript like:

<div id="xx" runat="server"></div>

Then at the server side,I want to get this control and fill some content to it,like:

FindControl("xx").Controls.Add(....);

It seems that this does not work. Since the server side process work before the client side process.

Any alternative idea?

Was it helpful?

Solution

Asp.net needs to know what controls are there on a page. It is non trivial to add elements in javascript and receive the data later into controls at the backend.

The correct way to do this is to add the controls at server side into the controls collection.

Refer: How to: Add Controls to an ASP.NET Web Page Programmatically

Label myLabel = new Label();
myLabel.ID = "myLabel";
myLabel.Text = "Sample Label";
Panel1.Controls.Add(myLabel);

When controls are added to the controls collection via someContainer.Controls.Add you can then find them using someContainer.FindControl

Label myLabel = (Label)someContainer.FindControl("myLabel");

You also need to be completely aware of the asp.net page life cycle, if you don't want any surprises when adding controls dynamically.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top