Recent Articles

Nested Form in ASP.NET Page

It's common practice on the web to copy and paste a third party HTML code to add functionality to a page. For example, PayPal provides HTML code for the webmaster to quickly incorporate a checkout button. In other instances, you can add a free banner that tells you the current weather conditions in your area. Google, and many other sites, even go as far as offering specialized services to enhance your page and they refer to them as "gadgets" or "widgets".

A sophisticated widget will likely include a HTML Form tag. To embed this kind of code is normally a breeze for even non-programmers. What appears to be easy is actually quite complicated to do on ASP.NET pages. The reason is because every ASP.NET page is wrapped in one big HTML Form. When you try to integrate the widget, you essentially end up with nested forms. Unfortunately, there is no such standard for nested form and it's specifically disallowed by browser standards. Most likely when you do that, your rendered page will look completely messed up or broken depending on the browser. On Internet Explorer and Firefox, the page will not render correctly and your web application losses postback capability. Please note that nested form is different from the concept of multi-form. The browser does support multiple forms, as long as they are not nested together.

There are several clever workarounds. Suppose you have the following gadget code:




Use an IFRAME

One method involves creating a plain HTML page and pasting the widget there. Change the target of the Form element to open in a new window or use _parent to submit back to the container page otherwise it will only reload inside the IFRAME. Then from your ASP.NET page, create an IFRAME that sources the HTML page you just created. You may also need to adjust the width and height for it to display nicely.

target="_parent" >


Force Submission to Navigate Using a GET Request

This approach will only work if the receiving host is willing to accept a GET request in place of a normal POST. To do that you exclude the Form tags and add an onClick event in the submit button to force a browser navigation.


onclick="location.href='http://www.example.com/do?email=' + this.form.email.value;" />

Dynamically Change the Form Action 

A more sophisticated way is completely override the default ASP.NET Form action using javascript. The drawback is you may end up posting more than the necessary information because you're telling the system to POST every data contained within the entire ASP.NET Form to a new location. This method assumes the receiving host will simply ignore those values. To use this approach, you remove the Form tags and add an onClick event in the submit button.


onclick="this.form.action='http://www.example.com/do';" />

Use a 3rd Party Form Handler

You can also download free and paid 3rd party ASP.NET controls that can adjust to make your widget work inside any ASP.NET page.