Click here to Skip to main content
11,492,907 members (61,753 online)
Click here to Skip to main content

Post an ASP.NET form with JavaScript

, 18 Jun 2003 520K 3.8K 111
Rate this:
Please Sign up or sign in to vote.
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.

<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

Share

About the Author

David Truxall
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 HP in the metropolitan Detroit area.
Follow on   Twitter

Comments and Discussions

 
GeneralMy vote of 5 Pin
hajivalie1-Oct-11 0:28
memberhajivalie1-Oct-11 0:28 
GeneralReport [modified] Pin
pradeep rawat2-May-11 2:54
memberpradeep rawat2-May-11 2:54 
GeneralRe form submit Pin
Ajay Kale New13-Oct-10 3:15
memberAjay Kale New13-Oct-10 3:15 
Generaltest [modified] Pin
pradeep rawat2-Sep-10 5:28
memberpradeep rawat2-Sep-10 5:28 
Generalproblem when using to redirect on two different pages Pin
Amit kumar pathak4-Jan-10 21:05
memberAmit kumar pathak4-Jan-10 21:05 
GeneralI am impressed Pin
daithy15-Nov-07 2:37
memberdaithy15-Nov-07 2:37 
GeneralBRILLIANT !!! Pin
davidhart31-Oct-07 6:37
memberdavidhart31-Oct-07 6:37 
GeneralPostBackUrl Pin
sharky1916-Aug-07 4:52
membersharky1916-Aug-07 4:52 
GeneralRe: PostBackUrl Pin
David Truxall20-Aug-07 2:36
memberDavid Truxall20-Aug-07 2:36 
GeneralRe: PostBackUrl Pin
sharky1920-Aug-07 3:34
membersharky1920-Aug-07 3:34 
sorry,i didn't pay attention to the date.
have a nice day.
GeneralShow confirmation pop-up before saving the data . Pin
inrakeshworld27-Jul-07 20:56
memberinrakeshworld27-Jul-07 20:56 
Questionnorton doesn't allow posting Pin
tlepers18-Jun-07 22:45
membertlepers18-Jun-07 22:45 
GeneralPOST to another Page/URL without js Pin
bdaniel73-Apr-07 6:15
memberbdaniel73-Apr-07 6:15 
GeneralEasier solution using DHTML Pin
csandvig14-Feb-07 14:25
membercsandvig14-Feb-07 14:25 
GeneralRe: Easier solution using DHTML Pin
David Truxall17-Feb-07 7:31
memberDavid Truxall17-Feb-07 7:31 
GeneralValidation of viewstate MAC failed error Pin
enteng.kabisote28-Nov-06 0:30
memberenteng.kabisote28-Nov-06 0:30 
GeneralRe: Validation of viewstate MAC failed error Pin
David Truxall28-Nov-06 13:34
memberDavid Truxall28-Nov-06 13:34 
Questionhow can i get the submit button name on another .aspx Pin
mdlipon7-Nov-06 2:12
membermdlipon7-Nov-06 2:12 
GeneralTo make a javascript function execute only at the time of closing a window and not while refreshing Pin
saleemy2ks25-Sep-06 19:19
membersaleemy2ks25-Sep-06 19:19 
GeneralRe: To make a javascript function execute only at the time of closing a window and not while refreshing Pin
vini2k115-Mar-07 21:02
membervini2k115-Mar-07 21:02 
GeneralTo avoid executing the javascript function written on onbeforeUnload event of a page when we refresh page [modified] Pin
saleemy2ks24-Sep-06 19:59
membersaleemy2ks24-Sep-06 19:59 
GeneralSo Useful Pin
morteza5731-Jul-06 0:59
membermorteza5731-Jul-06 0:59 
GeneralJust remove viewstate Pin
tom__14-Dec-05 13:23
membertom__14-Dec-05 13:23 
GeneralRe: Just remove viewstate Pin
morteza5731-Jul-06 1:00
membermorteza5731-Jul-06 1:00 
GeneralThank you Pin
Kas_Aspnet23-Nov-05 22:04
memberKas_Aspnet23-Nov-05 22:04 
GeneralAnother Approach Pin
JVMFX18-Jul-05 5:27
memberJVMFX18-Jul-05 5:27 
GeneralRe: Another Approach Pin
chalaco0124-Oct-06 11:59
memberchalaco0124-Oct-06 11:59 
GeneralLog in securely Pin
NascarRules29-Jun-05 13:07
memberNascarRules29-Jun-05 13:07 
GeneralDoes not work if using cookieless session Pin
MSolve23-Jun-05 10:03
memberMSolve23-Jun-05 10:03 
GeneralAwesome Pin
Anonymous8-May-05 17:48
sussAnonymous8-May-05 17:48 
QuestionSubmit the form to another aspx page if some condition is satisfied? Pin
senpost5-May-05 9:36
membersenpost5-May-05 9:36 
Questionhow to call client side function througn web server control Pin
maninat24-Aug-04 22:57
membermaninat24-Aug-04 22:57 
AnswerRe: how to call client side function througn web server control Pin
Anonymous25-Aug-04 21:26
sussAnonymous25-Aug-04 21:26 
GeneralRe: how to call client side function througn web server control Pin
Anonymous25-Aug-04 21:27
sussAnonymous25-Aug-04 21:27 
GeneralRe: how to call client side function througn web server control Pin
Anonymous25-Aug-04 21:34
sussAnonymous25-Aug-04 21:34 
Generalframes problem Pin
Anonymous24-Aug-04 20:14
sussAnonymous24-Aug-04 20:14 
GeneralPost to New Window Pin
pllms3-Jun-04 22:41
memberpllms3-Jun-04 22:41 
GeneralRe: Post to New Window Pin
David Truxall4-Jun-04 12:44
memberDavid Truxall4-Jun-04 12:44 
QuestionCan Post Form with example but but postback code cannot work Pin
pllms22-Feb-04 23:11
memberpllms22-Feb-04 23:11 
AnswerRe: Can Post Form with example but but postback code cannot work Pin
David Truxall23-Feb-04 17:58
memberDavid Truxall23-Feb-04 17:58 
Generalusing client script to reload page in other frame Pin
mansyno8-Feb-04 11:35
membermansyno8-Feb-04 11:35 
GeneralRe: using client script to reload page in other frame Pin
David Truxall9-Feb-04 10:26
memberDavid Truxall9-Feb-04 10:26 
GeneralRe: using client script to reload page in other frame Pin
mansyno9-Feb-04 12:22
membermansyno9-Feb-04 12:22 
GeneralRe: using client script to reload page in other frame Pin
David Truxall9-Feb-04 14:58
memberDavid Truxall9-Feb-04 14:58 
Generalpage.IsPostBack problem Pin
Hergass13-Jan-04 22:07
memberHergass13-Jan-04 22:07 
GeneralRe: page.IsPostBack problem Pin
David Truxall15-Jan-04 4:01
memberDavid Truxall15-Jan-04 4:01 
GeneralRe: page.IsPostBack problem Pin
John Steimann7-Jan-05 6:57
memberJohn Steimann7-Jan-05 6:57 
GeneralRe: page.IsPostBack problem Pin
kajalchatterjee2-Feb-05 21:13
memberkajalchatterjee2-Feb-05 21:13 
AnswerRe: page.IsPostBack problem Pin
AndyStephens9-May-06 2:10
memberAndyStephens9-May-06 2:10 
GeneralImprovement : Avoid problems with the &quot;Back&quot; button Pin
b_i_c_k29-Oct-03 0:10
sussb_i_c_k29-Oct-03 0:10 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150520.1 | Last Updated 19 Jun 2003
Article Copyright 2003 by David Truxall
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid