5,442,164 members and growing! (17,548 online)
Email Password   helpLost your password?
Web Development » ASP.NET » General     Intermediate

Post an ASP.NET form with JavaScript

By David Truxall

Use JavaScript to bypass the ASP.NET postback process and post an ASP.NET form to another location.
Javascript, C#Windows, .NET, .NET 1.1, Win2K, WinXP, Win2003, Visual Studio, ASP.NET, Dev

Posted: 18 Jun 2003
Updated: 18 Jun 2003
Views: 322,647
Bookmarked: 81 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
37 votes for this Article.
Popularity: 6.77 Rating: 4.32 out of 5
2 votes, 5.4%
1
0 votes, 0.0%
2
3 votes, 8.1%
3
6 votes, 16.2%
4
26 votes, 70.3%
5

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.

<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:

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:

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:

<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:

<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

About the Author

David Truxall


Dave has been programming for a living since 1995, working mainly with Microsoft technologies modelling internal business processes. He is currently employed by RCM Technologies in the metropolitan Detroit area.
Occupation: Web Developer
Location: United States United States

Other popular ASP.NET articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 25 of 56 (Total in Forum: 56) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralI am impressedmemberdaithy2:37 15 Nov '07  
GeneralBRILLIANT !!!memberdavidhart6:37 31 Oct '07  
GeneralPostBackUrlmembersharky194:52 16 Aug '07  
GeneralRe: PostBackUrlmemberDavid Truxall2:36 20 Aug '07  
GeneralRe: PostBackUrlmembersharky193:34 20 Aug '07  
GeneralShow confirmation pop-up before saving the data .memberinrakeshworld20:56 27 Jul '07  
Questionnorton doesn't allow postingmembertlepers22:45 18 Jun '07  
GeneralPOST to another Page/URL without jsmemberbdaniel76:15 3 Apr '07  
GeneralEasier solution using DHTMLmembercsandvig14:25 14 Feb '07  
GeneralRe: Easier solution using DHTMLmemberDavid Truxall7:31 17 Feb '07  
GeneralValidation of viewstate MAC failed errormemberenteng.kabisote0:30 28 Nov '06  
GeneralRe: Validation of viewstate MAC failed errormemberDavid Truxall13:34 28 Nov '06  
Questionhow can i get the submit button name on another .aspxmembermdlipon2:12 7 Nov '06  
GeneralTo make a javascript function execute only at the time of closing a window and not while refreshingmembersaleemy2ks19:19 25 Sep '06  
GeneralRe: To make a javascript function execute only at the time of closing a window and not while refreshingmembervini2k121:02 15 Mar '07  
GeneralTo avoid executing the javascript function written on onbeforeUnload event of a page when we refresh page [modified]membersaleemy2ks19:59 24 Sep '06  
GeneralSo Usefulmembermorteza570:59 31 Jul '06  
GeneralJust remove viewstatemembertom__13:23 14 Dec '05  
GeneralRe: Just remove viewstatemembermorteza571:00 31 Jul '06  
GeneralThank youmemberKas_Aspnet22:04 23 Nov '05  
GeneralAnother ApproachmemberJVMFX5:27 18 Jul '05  
GeneralRe: Another Approachmemberchalaco0111:59 24 Oct '06  
GeneralLog in securelymemberNascarRules13:07 29 Jun '05  
GeneralDoes not work if using cookieless sessionmemberMSolve210:03 3 Jun '05  
GeneralAwesomesussAnonymous17:48 8 May '05  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 18 Jun 2003
Editor: Smitha Vijayan
Copyright 2003 by David Truxall
Everything else Copyright © CodeProject, 1999-2008
Web09 | Advertise on the Code Project