I'm generating HTML elements on the fly using javascript. These controls are located within an update panel on the browser.
For some reason, I'm unable to access those elements in the Page.Form[] array.
Is there a reason for this?
My current solution creates an array of strings, turns that into a JSON string, stores that in a hidden variable which gets posted back to the server as the hidden field was defined before in server side code.
Markup
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<div id="dynamicInputsGoHere" class="hiddenContent" runat="server"></div>
</ContentTemplate>
Javascript to create inputs
fo开发者_JAVA百科r (i = currentSize; i < numberInputsToCreate; i++) {
html += "<input type='text' id='inputNum" + i.toString() + "' />";
}
$('#dynamicInputsGoHere').append(html);
I'm trying to access the dynamic inputs that were generated by javascript when the update panel posts back.
You need to give your input elements a name
attribute in order for them to get submitted with the form (and available in Request.Form
):
for (var i = currentSize; i < numberInputsToCreate; i++) {
var name = "inputNum" + i;
html += '<input type="text" id="' + name + '" name="' + name + '" />';
}
$('#dynamicInputsGoHere').append(html);
Then on the server, access them as:
string value0 = Request.Form["inputNum0"];
string value1 = Request.Form["inputNum1"];
string value2 = Request.Form["inputNum2"];
You're probably best to send numberInputsToCreate
in a hidden field (type="hidden"
) and use a loop on the server to pluck the values out.
I think it is not possible to access the HTML elements created by javascript in codebehind.
These controls don't have runat="server" property. So it is not possible to get those controls in codebehind.
Question: Does this programming exist inside a MasterPage or UserControl or any other control that implements INamingContainer
? Check your renedered HTML and make sure that you do in fact have a <div id="dynamicInputsGoHere">
since you have it set as runat="server"
you could very well have something like <div id="ctrl0_dynamicInputsGoHere">
and therefor your jQuery won't execute.
Once you've verified the input's are being found by your script you'll probably want to register script with the scriptmanager (just to be safe since you are using the UpdatePanel.)
ScriptManager.RegisterStartupScript(this, this.GetType(), "createinputs", @";for (var i = currentSize; i < numberInputsToCreate; i++) {
var name = ""inputNum"" + i;
html += '<input type=""text"" id=""' + name + '"" name=""' + name + '"" />';
}
$('#dynamicInputsGoHere').append(html);", true);
When your looking for values in code behind you'll have to check in Request.Form["inputNum"+i]
.
精彩评论