Skip Navigation | Groups

This site uses cookies- for more information see the Cookie Policy | Continue

Tags

.NET

2014110201 Email to Ronx
 

Simulate Multiple Forms in asp.NET Page


An .aspx page can, as a general rule, only contain one form. However, with a little code, the page can appear to contain multiple forms.

In the example below two forms each have a text box for input. Pressing the appropriate submit button will process the associated form, and display the result (in these forms the result is the inputted text reversed). Note that pressing the Enter key will normally submit a form. However, since an .aspx page only has one form pressing Enter will be equivalent to pressing the first submit button on the page. In this example the Enter key is suppressed to avoid this - forcing the user to click the appropriate button.

The HTML for the forms is here, with the (VB.net) code behind.

Example

Form 1


 

Form 2


HTML

<asp:Panel ID="Panel1" runat="server" GroupingText="Form 1">
<p><asp:TextBox runat="server" id="Form1TBox1"></asp:TextBox><br />
<asp:Button id="Button1" runat="server" Text="Button" /></p>
<p id="res1" runat="server">&nbsp;</p>
</asp:Panel>
<p>&nbsp;</p>
<asp:Panel id="Panel2" runat="server" GroupingText="Form 2">
<p><asp:TextBox runat="server" id="Form2TBox1"></asp:TextBox><br />
<asp:Button id="Button2" runat="server" Text="Button" /></p>
<p id="res2" runat="server">&nbsp;</p>
</asp:Panel>

Code Behind

Protected Sub page_load(sender As Object, e As EventArgs)
'on page load, add event handler to text boxes to trap Enter key
'All form elements (except HTML text areas or aspx multiline textboxes 
'must have the enter key trapped
Form1TBox1.Attributes.Add("onkeydown", "return (event.keyCode!=13);")
Form2TBox1.Attributes.Add("onkeydown", "return (event.keyCode!=13);")
'clear results
resForm1.InnerText = ""
resForm2.InnerText = ""
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Code to process Form1 input fields
'This code omits code injection suppression
Dim tmp As String = ""
Dim stxt As String = ""
stxt = Form1TBox1.Text
If stxt <> "" Then
For ii As Integer = Len(stxt) To 1 Step -1
tmp &= Mid(stxt, ii, 1)
Next
resForm1.InnerText = tmp
Else
'Message if textbox is empty
resForm1.InnerText = "Need some valid input"
End If
End Sub
 
Protected Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
'Code to process Form2 input fields
'This code omits code injection suppression
 
Dim tmp As String = ""
Dim stxt As String = ""
stxt = Form2TBox1.Text
If stxt <> "" Then
For ii As Integer = Len(stxt) To 1 Step -1
tmp &= Mid(stxt, ii, 1)
Next
resForm2.InnerText = tmp
Else
'Message if textbox is empty
resForm2.InnerText = "Need some valid input"
End If
End Sub