Kirk Evans Blog

.NET From a Markup Perspective

Neat ASP.NET Trick: Multiple Forms on a Page

Tinkering around today, and I figured out a weird trick with ASP.NET 1.1.  If you try to add 2 forms to an ASP.NET page, you get a nice error:


A page can have only one server-side Form tag.


Apparently, that message should be augmented to read:


A page can have only one visible server-side Form tag.


The form has a .Visible property, which we can toggle back and forth.  The default value is true, and only the HTML for the visible form is rendered to the client.  If a form’s .Visible property is false, it can still coexist on the page, it just is not rendered to the client.  This could be interesting for implementing something similar to the wizard control in ASP.NET 2.0.

<%@ Page language=”c#” %>
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN” >
<HTML>
<HEAD>
<title>WebForm1</title>
<script runat=server language=”C#”>
private void Page_Load(object sender, System.EventArgs e)
{
Form1.Visible = !Form1.Visible;
Form2.Visible = !Form2.Visible;
}
</script>
</HEAD>

<body MS_POSITIONING=”GridLayout”>
<form id=”Form1″ method=”post” runat=”server” >
<asp:TextBox id=”Textbox2″ runat=”server”>Form1</asp:TextBox>
<asp:Button Runat=server ID=”Button1″ NAME=”Button1″ Text=”Click to see Form2″/>
</form>
<form id=”Form2″ method=”post” runat=”server” visible=”false”>
<asp:TextBox id=”TextBox1″ runat=”server”>Form2</asp:TextBox>
<asp:Button Runat=server ID=”Button2″ NAME=”Button2″ Text=”Click to see Form1″/>
</form>
</body>
</HTML>