May 15, 2005
Custom Control to Wrap Forms on an ASP.NET Page
Problem: Can not paste a simple HTML form into an ASP.NET page.
Cause: The ASP.NET Page class gets confused and starts loosing track of server controls (which leads to the oh-so-helpful "Object reference not set to an instance of an object." message).
My solution is a custom user control that you a use to wrap the form. The control will parse the form, removing all the stuff that confuses the ASP.NET Page class. It also converts each submit button into a server control and attaches event handlers that convert clicks into the appropriate action.
The entire control is in a single file. All of the documentation is in the control source as comments. To use this control follow these steps:
- Copy FormWrapper.ascx to your site.
- Place this line at the top of the page:
<%@ Register TagPrefix="solutions" TagName="FormWrapper" Src="FormWrapper.ascx" %>
- Add these tags where you want the new sub-form to appear on the page:
<solutions:FormWrapper id="FW" runat="server">
</solutions:FormWrapper>
- Copy and paste the form you want to add between the FormWrapper tags like this:
<solutions:FormWrapper id="FW" runat="server">
<!-- Paste your form here -->
</solutions:FormWrapper>
Here's an example,
<solutions:FormWrapper id="FW" runat="server">
<form name="test" action="http://company.com/submit.asp">
<input type="text" name="name">
</form>
</solutions:FormWrapper>
Notes
If your form comes with a <script> block, you can paste that inside the wrapper as well. There are a couple of options you can add to the FormWrapper tag. Normally the form will be submitted from the server hosting the page. If you would prefer to have the form submitted from the client, add SubmitFrom="Client". The source comments describe some caveats to both techniques.
If your form includes some validation (in the guise of an onsubmit event handler), this is normally stripped off so that the rest of the page can be submitted even if your sub-form is not filled in. However, if your sub-form is the only important thing on the page and must be validated, add EnableOnsubmit="True". This will attach the onsubmit handler to the ASP.NET Page.
Please put quotes around tag attributes in your form (i.e. method="post" rather than method=post). Otherwise ASP.NET may have a hard time parsing the form. If you see an that FormWrapper does not have a property XXX, or if the submit button does not seem to do anything (or do the wrong thing) then it's a pretty good bet that you are missing some quotes somewhere in the form.
FormWrapper.zip (4.92 KB)
This site looks much better in a browser that supports current web standards, but it is accessible to any browser.
Download one now
Some parts of this site will not work effectively on this older browser.
Please consider
updating your browser