Accessing client side dynamic controls within ASP.NET codebehind
Hi I'm trying to access the html controls that are created dynamically within an event but I'm unable to access this.
I'm using the following code to create the elements on the client side using Javascript:
function addInput(field)
{
...declaratives...
var input = document.createElement("input");
input.id = field+count;
input.name = field+count;
input.type = "text";
... remainder of the code and the element is added to the DOM...
}
I also have a server control on the page (a button called Button1), and what I want to do is when the user clicks on the button I want to look at the details in that the user has entered in the dynamically created input boxes and store them in a database. However, in the event protected void Button1_Click(object sender, EventArgs e)
I can't access the input fields.
Is this possible开发者_运维技巧 ?
I'm using VS 2010 C# (v4.0).
Well your adding client-side HTML controls via JavaScript - ASP.NET will not see those (they're not runat=server, this needs to be render-time, not after the page has loaded).
What you can do is add "name" attributes to all your elements (which you've done), then when you submit the form (with the Button click), you can check the form elements via the Request.Form
collection.
protected void Button1_Click(object sender, EventArgs e)
{
var inputValue = Request.Form["someId"];
}
You might also need to set AutoPostBack="true"
on the button, so it submits the form when you click the button.
HTH
The reason why dynamic input controls only show up when there is at-least 1 static is because the form needs the enctype="multipart/form-data" to upload files and asp.net adds that when you have 1 static file control. To have no static file input controls, you can set the enctype="multipart/form-data" attribute for the form manually in the aspx markup or in code-behind: Page.Form.Attributes.Add("enctype", "multipart/form-data");
I would make sure that the input fields are added to an existing form element in the DOM. Also, I've had problems in the past with adding dynamic input (file) controls to a form, and .NET cannot see them... Unless there is at least one statically defined file input in the form already.
精彩评论