Click here to Skip to main content
15,867,290 members
Articles / Web Development / ASP.NET
Article

Post an ASP.NET form with JavaScript

Rate me:
Please Sign up or sign in to vote.
4.59/5 (40 votes)
18 Jun 20034 min read 620.7K   4K   111   62
Use JavaScript to bypass the ASP.NET postback process and post an ASP.NET form to another location.

Introduction

One of the biggest changes from ASP to ASP.NET is the postback process. By design, ASP.NET pages post form data back to themselves for processing. For most situations, this is an acceptable process. But if a page must post form data to another site or another ASP.NET page, this is impractical. The current ASP.NET postback process supports lots of ways to manage this process.

  1. Use Server.Transfer() to send posted fields to another page. This has the unfortunate side effect of not changing the user's URL.
  2. Pass the items on a querystring, bundling them manually and using Response.Redirect() to send the new querystring to another page. The querystring has both security and length issues.
  3. Pass the items on a post. Create a custom function to read the current items and send them via an HTTP post.
  4. Use an HTML form instead of a web form. Remove the runat="server" attribute from the Form tag. Unfortunately, the validator controls can no longer be used, and that is the main reason I decided to use a JavaScript solution.
  5. Use a simple JavaScript function to alter the page behavior on the client.

I am going to describe a technique using a simple client-side JavaScript. The advantage of this is that it is quick and simple, especially for developers just starting out with ASP.NET or for simple applications. Additionally, when migrating ASP applications to ASP.NET, this little technique can help reduce migration time by allowing you to keep, the ASP page-to-page posting behavior. The one downside is that users can choose to operate their browser without JavaScript, thus negating this technique. If this is a serious concern for you, look into the third option listed above.

Background

There are two problems to overcome when using JavaScript to change the posting behavior of ASP.NET. The first problem is the self-postback. JavaScript allows the action attribute of the HTML Form tag to be changed on the client. It is the content of the post that causes ASP.NET to have the most serious problems. When an ASP.NET page receives a post, it checks for a field called __VIEWSTATE (that's 2 underscore symbols) in the post. ASP.NET is using this field for many reasons, most outside the scope of this article. But, one thing the __VIEWSTATE field does contain is internal validation for ASP.NET. If you simply post the __VIEWSTATE field to a different ASP.NET page, than the page that filled the __VIEWSTATE field, ASP.NET will throw an exception:

"The viewstate is invalid for this page and might be corrupted."

If we attempt to remove the data from the __VIEWSTATE field prior to a post with JavaScript, the same exception is thrown.

So, in order to post to another ASP.NET page, the __VIEWSTATE field cannot be passed to the next ASP.NET page. JavaScript allows us to rename the __VIEWSTATE field and change the action attribute of the form tag.

Using the code

In the HTML portion of our ASP.NET page, we need to include the JavaScript function, NoPostBack. It could reside in a separate file, but is included here in the page for simplicity.

JavaScript
<script language="javascript">
function noPostBack(sNewFormAction)
{
    document.forms[0].action = sNewFormAction;
    document.forms[0].__VIEWSTATE.name = 'NOVIEWSTATE';
}
</script>

The first line sets the form's action attribute to a new location that is passed to the function. The second line renames the __VIEWSTATE field. It can be called anything other than it's original name or the name of your other form items. If you are trying to save bandwidth, you could also set the value of the __VIEWSTATE field to "". In the ASP.NET Page_Load function, only one line of code is necessary:

C#
private void Page_Load(object sender, System.EventArgs e)
{
    Submit.Attributes.Add("onclick", "noPostBack('secondform.aspx');");
}

This adds an onclick attribute to the Submit button, and in this attribute we are specifying the new page or location for the post. When the button is clicked, it calls the JavaScript function before the form post occurs, changing the default location from the page itself to somewhere else.

If the data is posted to another ASP.NET form, simply handle the form items using Request.Form syntax:

C#
private void Page_Load(object sender, System.EventArgs e)
{
    Result.Text = Request.Form["SomeText"].ToString();
}

Points of interest

When dealing with Netscape 4 and a CSS-based layout, the JavaScript needs to adapt slightly. Each <div> is considered a layer, so you must address the layer specifically in the JavaScript. Assume the form is contained inside of a <div> named Content:

HTML
<div id="Content" name="Content">
    <form method="post" id="Form1" runat="server">

    </form>
</div>

The JavaScript now needs to differentiate between Netscape 4 and the other DOM aware browsers. Check for document.layers to identify Netscape 4, and simply use the syntax appropriate for that browser:

JavaScript
<script language="javascript">
<!--
function noPostBack(sNewFormAction)
{
    if(document.layers) //The browser is Netscape 4
    {
        document.layers['Content'].document.forms[0].__VIEWSTATE.name = 
                                                           'NOVIEWSTATE';
        document.layers['Content'].document.forms[0].action = 
                                                     sNewFormAction;
    }
    else //It is some other browser that understands the DOM
    {
        document.forms[0].action = sNewFormAction;
        document.forms[0].__VIEWSTATE.name = 'NOVIEWSTATE';
    }
}
-->
</script>

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Team Leader Hewlett-Packard
United States United States
Dave has been programming for a living since 1995, working previously with Microsoft technologies modeling internal business processes, and now working as a mobile architect and team lead. He is currently employed by DXC.technology in the metropolitan Detroit area.

Comments and Discussions

 
GeneralRe: how to call client side function througn web server control Pin
Anonymous25-Aug-04 20:34
Anonymous25-Aug-04 20:34 
Generalframes problem Pin
Anonymous24-Aug-04 19:14
Anonymous24-Aug-04 19:14 
GeneralPost to New Window Pin
pllms3-Jun-04 21:41
pllms3-Jun-04 21:41 
GeneralRe: Post to New Window Pin
David Truxall4-Jun-04 11:44
David Truxall4-Jun-04 11:44 
QuestionCan Post Form with example but but postback code cannot work Pin
pllms22-Feb-04 22:11
pllms22-Feb-04 22:11 
AnswerRe: Can Post Form with example but but postback code cannot work Pin
David Truxall23-Feb-04 16:58
David Truxall23-Feb-04 16:58 
Generalusing client script to reload page in other frame Pin
mansyno8-Feb-04 10:35
mansyno8-Feb-04 10:35 
GeneralRe: using client script to reload page in other frame Pin
David Truxall9-Feb-04 9:26
David Truxall9-Feb-04 9:26 
I tried what you described. I created a quick example made of 4 pages:

twoframe.html
<html>
<frameset rows="50%, *" frameborder="1">
    <frame name="top" src="topframe.aspx">

    <frame name="bottom" src="bottomframe.aspx">

</frameset>
</html>
</code>


topframe.aspx and newtop.aspx that are essentially empty, just some text so I can see what page is loading.

Here is what I put in bottomframe.aspx:

<%@ Page Language="VB" %>
<script runat="server">

Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
      Test.text = "Try This"
      Test.attributes.add("onclick","LoadReport()")
      if IsPostback then
        Posted.Text = "I posted back"
      end if
end sub
</script>
<html>
    <head>
        <script language="javascript">
        function LoadReport(){
            alert('In Function');
            parent.frames(0).location.href = "newtop.aspx"
        }
       </script>
    </head>
    <body>
        <h2>Bottom</h2>
        <form runat="server">
            <asp:Button id="Test" runat="server" Text="Button"></asp:Button>
            <asp:label id="Posted" runat="server"></asp:label>
        </form>
    </body>
</html>

</code>


When I click the button, here is what happens:

  1. Client function "LoadReport" fires
  2. Top frame reloads new page
  3. Postback occurs, label is updated


I hope this helps illustrate when the events are firing. I am not sure why the client event doesn't seem to happen for you. Make sure the client code fires by adding an alert or some other visible result to confirm that it really happens.

Dave
GeneralRe: using client script to reload page in other frame Pin
mansyno9-Feb-04 11:22
mansyno9-Feb-04 11:22 
GeneralRe: using client script to reload page in other frame Pin
David Truxall9-Feb-04 13:58
David Truxall9-Feb-04 13:58 
Generalpage.IsPostBack problem Pin
Hergass13-Jan-04 21:07
Hergass13-Jan-04 21:07 
GeneralRe: page.IsPostBack problem Pin
David Truxall15-Jan-04 3:01
David Truxall15-Jan-04 3:01 
GeneralRe: page.IsPostBack problem Pin
John Steimann7-Jan-05 5:57
John Steimann7-Jan-05 5:57 
GeneralRe: page.IsPostBack problem Pin
kajalchatterjee2-Feb-05 20:13
kajalchatterjee2-Feb-05 20:13 
AnswerRe: page.IsPostBack problem Pin
AndyStephens9-May-06 1:10
AndyStephens9-May-06 1:10 
GeneralImprovement : Avoid problems with the &quot;Back&quot; button Pin
b_i_c_k28-Oct-03 23:10
sussb_i_c_k28-Oct-03 23:10 
Generalcan't post form with the example code Pin
lamquoc14-Oct-03 11:13
lamquoc14-Oct-03 11:13 
GeneralRe: can't post form with the example code Pin
David Truxall14-Oct-03 15:29
David Truxall14-Oct-03 15:29 
GeneralRe: can't post form with the example code Pin
lamquoc14-Oct-03 18:23
lamquoc14-Oct-03 18:23 
GeneralRe: can't post form with the example code Pin
David Truxall15-Oct-03 2:48
David Truxall15-Oct-03 2:48 
GeneralRe: can't post form with the example code Pin
lamquoc15-Oct-03 4:17
lamquoc15-Oct-03 4:17 
GeneralUsing javascript in asp.net Pin
Majid Shahabfar20-Aug-03 1:41
Majid Shahabfar20-Aug-03 1:41 
GeneralRe: Using javascript in asp.net Pin
David Truxall20-Aug-03 11:32
David Truxall20-Aug-03 11:32 
GeneralOther Solutions Available Pin
Paul Wilson19-Jun-03 13:00
Paul Wilson19-Jun-03 13:00 
General[OT] Welcome Paul Pin
Thomas Freudenberg19-Jun-03 23:28
sussThomas Freudenberg19-Jun-03 23:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.