Click here to Skip to main content
Click here to Skip to main content

Post an ASP.NET form with JavaScript

By , 18 Jun 2003
 

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
Architect Compuware
United States United States
Member
Dave has been programming for a living since 1995, working previously with Microsoft technologies modelling internal business processes, and now working as a mobile architect. He is currently employed by Compuware in the metropolitan Detroit area.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberhajivalie30 Sep '11 - 23:28 
مرسی
GeneralReport [modified]memberpradeep rawat2 May '11 - 1:54 
<a href="http://www.microsoft.com/downloads/en/details.aspx?FamilyId=9F783224-9871-4EEA-B1D5-F3140A253DB6&displaylang=en">http://www.microsoft.com/downloads/en/details.aspx?FamilyId=9F783224-9871-4EEA-B1D5-F3140A253DB6&displaylang=en</a>[<a href="http://www.microsoft.com/downloads/en/details.aspx?FamilyId=9F783224-9871-4EEA-B1D5-F3140A253DB6&displaylang=en" target="_blank" title="New Window">^</a>]
 
<a href="http://www.mssqltips.com/tip.asp?tip=1690">http://www.mssqltips.com/tip.asp?tip=1690</a>[<a href="http://www.mssqltips.com/tip.asp?tip=1690" target="_blank" title="New Window">^</a>]
 
<a href="http://www.mssqltips.com/tutorial.asp?tutorial=226">http://www.mssqltips.com/tutorial.asp?tutorial=226</a>[<a href="http://www.mssqltips.com/tutorial.asp?tutorial=226" target="_blank" title="New Window">^</a>]
 
<a href="http://www.mssqltips.com/tutorial.asp?tutorial=222">http://www.mssqltips.com/tutorial.asp?tutorial=222</a>[<a href="http://www.mssqltips.com/tutorial.asp?tutorial=222" target="_blank" title="New Window">^</a>]
 

 
-- Modified Monday, May 2, 2011 11:15 AM
GeneralRe form submitmemberAjay Kale New13 Oct '10 - 2:15 
Hi ,
 
I am submitting a html form in ASP.NET 1.1, to a websphere server. I am browsing excel file and submitting through ActiveX object to Websphere server, by sybmitting form with action as Websphere hosted address.
 
Whenever I login to app, and try to upload the file with above functionality, for the first time, I get redirected to Login.aspx automatically. But when I re-login again and does the same thing as above, the file is uploaded successfully.
 
Can you please help me regarding this, as I have maintained releative values of timeout for session and form-authentication in web.config file.
 
- Ajay K
Generaltest [modified]memberpradeep rawat2 Sep '10 - 4:28 
/////////////////////////////////////////////////////////////////////////////////////
 
#include &lt;iostream&gt;
 
string StringToUpper(string);
string StringToLower(string);
 
int main(){
 
     string strInput = "UPPER TO LOWER:ABC";
            string strOutput = StringToLower(strInput);
     cout &lt;&lt; strOutput;
     cout &lt;&lt; "\n";
            strInput = "lower to upper:xyz";
            strOutput = StringToUpper(strInput);
     cout &lt;&lt; strOutput;    
            return 0;              
 
}
string StringToUpper(string strToConvert)
{
   //change each element of the string to upper case
   for(unsigned int i=0;i&lt;strToConvert.length();i++)
   {
         strToConvert[i] = std::toupper(strToConvert[i]);
   }
   return strToConvert;//return the converted string
}
string StringToLower(string strToConvert)
{
   //change each element of the string to upper case
   for(unsigned int i=0;i&lt;strToConvert.length();i++)
   {
         strToConvert[i] = std::tolower(strToConvert[i]);
   }
   return strToConvert;//return the converted string
}
-------------------------------------------------------------------------------------
Output:
upper to lower:abc
LOWER TO UPPER:XYZ
-------------------------------------------------------------------------------------
 

-------------------------------------------------------------------------------------
/////////////////////////////////////////////////////////////////////////////////////
#include &lt;iostream&gt;
int main ()
{    
int n;
cout &lt;&lt; "Enter length: ";
cin &gt;&gt; n;
cout &lt;&lt; endl;
for (int row=0; row&lt;=n; row++)
   {
      for (int col=n; col&gt;row; col--)
      {
         cout&lt;&lt;'*';
      }
   cout &lt;&lt; endl;   // end the line.
   }
return 0;
}
-------------------------------------------------------------------------------------
Output:
Enter length:
6
******
*****
****
***
**
*
|||||||||||||Test With Different Inputs||||||||||||||||||||
Enter length:
5
*****
****
***
**
*
-------------------------------------------------------------------------------------
 
-------------------------------------------------------------------------------------
/////////////////////////////////////////////////////////////////////////////////////
#include &lt;iostream&gt;
int main ()
{
string strInput;
cout &lt;&lt; "Enter alphabets in sequence i.e., (ABCDEFG): ";
cin &gt;&gt; strInput;
cout &lt;&lt; endl;
for (unsigned int row=0; row&lt;strInput.length(); row++)
   {
      for (unsigned int col=0; col&lt;=row; col++)
      {
         cout&lt;&lt;strInput[col];
      }
   cout &lt;&lt; endl;   // end the line.
   }
return 0;
}
-------------------------------------------------------------------------------------
Output:
 
Enter alphabets in sequence i.e., (ABCDEFG): ";
ABCDE
A
AB
ABC
ABCD
ABCDE
|||||||||||||Test With Different Inputs||||||||||||||||||||
Enter alphabets in sequence i.e., (ABCDEFG): ";
ABCDEF
A
AB
ABC
ABCD
ABCDE
ABCDEF
-------------------------------------------------------------------------------------
 

 
-------------------------------------------------------------------------------------
/////////////////////////////////////////////////////////////////////////////////////
#include &lt;iostream.h&gt;
int main()
{
int a, b, c, e, n=4, t=1, m=0;
for (a = e = 1; a&lt;=n; e++, n--) {
for (b = 1; b&lt;n; b++)
cout &lt;&lt; " ";
for (c = 1; 2*e - 1 &gt;= c; c++)
{
if(c&lt;=1)
{
   m++;
   cout &lt;&lt; m;
}
else
{
if(t==0)
{
   m++;
   cout &lt;&lt; m;
   t=1;
}
else
{
   cout &lt;&lt; " ";
   t=0;
}
}
}
 
cout &lt;&lt; endl;
}
return 0;
}
-------------------------------------------------------------------------------------
Output:
   1
   2 3
4 5 6
7 8 9 10
 
-------------------------------------------------------------------------------------
 
-------------------------------------------------------------------------------------
/////////////////////////////////////////////////////////////////////////////////////
#include &lt;iostream.h&gt;
int main()
{
int a, b, c, e, n=4, t=1, m=0;
for (a = e = 1; a&lt;n; e++, n--) {
for (b = 1; b&lt;n; b++)
cout &lt;&lt; " ";
for (c = 1; 2*e - 1 &gt;= c; c++)
{
if(c&lt;=1)
{
   m++;
   if(m==4)
   {
      cout &lt;&lt; "   ";
   }
   cout &lt;&lt; m;
}
else
{
if(t==0)
{
   if(m&lt;=3)
   {
      m++;  
      cout &lt;&lt; m;  
      t=1;
   }
}
else
{
      cout &lt;&lt; " ";
      t=0;
}
}
}
 
cout &lt;&lt; endl;
}
return 0;
}
************************************************************************************
Another Solution
************************************************************************************
#include &lt;iostream&gt;
int main ()
{    
cout &lt;&lt; " 1 ";
cout &lt;&lt; endl;
cout &lt;&lt; "2 3";
cout &lt;&lt; endl;
cout &lt;&lt; " 4 ";
return 0;
}
-------------------------------------------------------------------------------------
Output:
   1
   2 3
   4
-------------------------------------------------------------------------------------
 
-------------------------------------------------------------------------------------
/////////////////////////////////////////////////////////////////////////////////////
#include &lt;iostream.h&gt;
int main()
{
int num1,num2,num3,largeNum;
cout &lt;&lt; "Enter first number: ";
cin &gt;&gt; num1;
cout &lt;&lt; "Enter second number: ";
cin &gt;&gt; num2;
cout &lt;&lt; "Enter thirld number: ";
cin &gt;&gt; num3;
if(num1&gt;num2)
{
if(num1&gt;num3)
   largeNum=num1;
else
   largeNum=num3;
}
else
{
if(num2&gt;num3)
   largeNum=num2;
else
   largeNum=num3;
}
 
cout &lt;&lt; "Large number is: ";
cout &lt;&lt; largeNum;
return 0;
}
 
-------------------------------------------------------------------------------------
Output:
Enter first number:
1
Enter second number:
2
Enter thirld number:
3
Large number is: 3
-------------------------------------------------------------------------------------
 
-------------------------------------------------------------------------------------
/////////////////////////////////////////////////////////////////////////////////////
#include &lt;iostream.h&gt;
int main()
{
string str1,str2,str3;
cout &lt;&lt; "Enter first string: ";
cin &gt;&gt; str1;
cout &lt;&lt; "Enter second string: ";
cin &gt;&gt; str2;
cout &lt;&lt; endl;   // end the line.
cout &lt;&lt; "Frist String: " + str1;
cout &lt;&lt; endl;   // end the line.
cout &lt;&lt; "Second String: " + str2;
str3=str1;
str1=str2;
str2=str3;
cout &lt;&lt; endl;   // end the line.
cout &lt;&lt; "After copy:";
cout &lt;&lt; endl;   // end the line.
cout &lt;&lt; "Frist String: " + str1;
cout &lt;&lt; endl;   // end the line.
cout &lt;&lt; "Second String: " + str2;
return 0;
}
 
-------------------------------------------------------------------------------------
Enter first string:
A
Enter second string:
B
Frist String: A
Second String: B
After copy:
Frist String: B
Second String: A
-------------------------------------------------------------------------------------
 
-------------------------------------------------------------------------------------
/////////////////////////////////////////////////////////////////////////////////////
#include &lt;iostream.h&gt;
int main()
{
string str1,str2;
cout &lt;&lt; "Enter first string: ";
cin &gt;&gt; str1;
cout &lt;&lt; "Enter second string: ";
cin &gt;&gt; str2;
cout &lt;&lt; endl;   // end the line.
cout &lt;&lt; "Frist String: " + str1;
cout &lt;&lt; endl;   // end the line.
cout &lt;&lt; "Second String: " + str2;
cout &lt;&lt; endl;   // end the line.
cout &lt;&lt; "After Concatenation:";
cout &lt;&lt; endl;   // end the line.
cout &lt;&lt; str1 + str2;
return 0;
}
-------------------------------------------------------------------------------------
Output:
Enter first string:
A
Enter second string:
B
Frist String: A
Second String: B
After Concatenation:
AB
-------------------------------------------------------------------------------------
 
-------------------------------------------------------------------------------------
/////////////////////////////////////////////////////////////////////////////////////
#include &lt;iostream.h&gt;
int main()
{
float radius,pi=3.1416,output;
int choice=2;
cout &lt;&lt; "Enter radius of circle: ";
cin &gt;&gt; radius;
cout &lt;&lt; "Enter your choice: Area=0, Perimeter=1: ";
cin &gt;&gt; choice;
 
switch(choice)
{
case 0:
      output=pi*radius*radius;
      cout &lt;&lt; "Area: ";
      cout &lt;&lt; output;
      break;
case 1:
      output=2*pi*radius;
      cout &lt;&lt; "Perimeter: ";
      cout &lt;&lt; output;
      break;  
default:
         cout &lt;&lt; "Wrong Choice !";
         break;
}
 
return 0;
}
 
-------------------------------------------------------------------------------------
Output:
Enter radius of circle:
3
Enter your choice: Area=0, Perimeter=1:
0
Area: 28.2744
|||||||||||||Test With Different Inputs||||||||||||||||||||
Enter radius of circle:
3
Enter your choice: Area=0, Perimeter=1:
1
Perimeter: 18.8496
|||||||||||||Test With Different Inputs||||||||||||||||||||
Enter radius of circle:
3
Enter your choice: Area=0, Perimeter=1:
2
Wrong Choice !
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
/////////////////////////////////////////////////////////////////////////////////////
#include &lt;iostream&gt;
int main ()
{    
int n;
string bline;
cout &lt;&lt; "Enter square side length: ";
cin &gt;&gt; n;
cout &lt;&lt; endl;   // end the line.
for (int i=1; i&lt;=n; i++)
   {
   cout&lt;&lt;"* ";
   bline+="* ";
   if(i==n)
   {
      cout &lt;&lt; endl;   // end the line.
      for (int j=1; j&lt;=n-2; j++)
      {
         cout&lt;&lt;"* ";
         for (int k=1; k&lt;=n-2; k++)
         {
            cout&lt;&lt;"   ";
         }
         cout&lt;&lt;"* ";
         cout &lt;&lt; endl;   // end the line.
      }
      cout &lt;&lt; bline;
      }
   }
return 0;
}
 
-------------------------------------------------------------------------------------
Output:
Enter square side length:
5
* * * * *
*         *
*         *
*         *
* * * * *
|||||||||||||Test With Different Inputs||||||||||||||||||||
Enter square side length:
4
* * * *
*      *
*      *
* * * *
-------------------------------------------------------------------------------------
 
-------------------------------------------------------------------------------------
/////////////////////////////////////////////////////////////////////////////////////
#include &lt;iostream&gt;
#include &lt;math.h&gt;
using namespace std;
int main ()
{
int a=0,b=4,c=6;
cout &lt;&lt; "Enter A: ";
cin &gt;&gt; a;
cout &lt;&lt; "Enter B: ";
cin &gt;&gt; b;
cout &lt;&lt; "Enter C: ";
cin &gt;&gt; c;
if(a!=0)
   {
      float d;
      d=b*b-4*a*c;//this is the discriminant.
      cout &lt;&lt; d;
      cout &lt;&lt; endl;
      if(d&gt;0)//if d&gt;0 then the equation has two roots.
      {
         float x1,x2;
         x1=(-b*sqrt(d))/(2*a);
         x2=(-b-sqrt(d))/(2*a);
         cout &lt;&lt; "x=" &lt;&lt; x1 &lt;&lt; " OR x=" &lt;&lt; x2 &lt;&lt; endl;
      }
      else if(d==0)//if d=0 it has a double root.
      {
         float x;
         x=(-b)/(2*a);
         cout &lt;&lt; "x=" &lt;&lt; x &lt;&lt; endl;
      }
      else
      {
         cout &lt;&lt; "It has no root.";
      }
   }  
   else
   {
      if(b!=0)//if a=0 and b!=0 it has one root. (It's linear)
      {
         float x;
         x=(-c)/b;
         cout &lt;&lt; "x=" &lt;&lt; x &lt;&lt; endl;
      }
      else
      {
         if(c!=0)
            {
               cout &lt;&lt; "No Root.";
            }
            else
            {
               cout &lt;&lt; "Indefinite.";
            }
      }
   }     
return 0;
}
 
-------------------------------------------------------------------------------------
Output:
Enter A:
2
Enter B:
3
Enter C:
4
It has no root.
|||||||||||||Test With Different Inputs||||||||||||||||||||
Enter A:
2
Enter B:
10
Enter C:
4
x=-20.6155 OR x=-4.56155
|||||||||||||Test With Different Inputs||||||||||||||||||||
Enter A:
2
Enter B:
4
Enter C:
2
x=-1
|||||||||||||Test With Different Inputs||||||||||||||||||||
Enter A:
0
Enter B:
4
Enter C:
8
x=-2
|||||||||||||Test With Different Inputs||||||||||||||||||||
Enter A:
0
Enter B:
0
Enter C:
2
No Root.
|||||||||||||Test With Different Inputs||||||||||||||||||||
Enter A:
0
Enter B:
0
Enter C:
0
Indefinite.
-------------------------------------------------------------------------------------
 

 
-- Modified Friday, September 3, 2010 5:49 AM
Generalproblem when using to redirect on two different pagesmemberAmit kumar pathak4 Jan '10 - 20:05 
below is my condition on button click
 
IF condition is i=2 then "IMG_LOGIN.Attributes.Add("onclick", "noPostBack('http://web5.server.com/AuthUser.aspx');");" line executes and if next time click on button and i=1 still page moves "'http://web5.server.com/AuthUser.aspx'" instead of "'http://web4.server.com/AuthUser.aspx'".
 
if (i==1)
IMG_LOGIN.Attributes.Add("onclick", "noPostBack('http://web4.server.com/AuthUser.aspx');");
else
IMG_LOGIN.Attributes.Add("onclick", "noPostBack('http://web5.server.com/AuthUser.aspx');");
GeneralI am impressedmemberdaithy15 Nov '07 - 1:37 
Thanks so much to the author of this article. I was facing an issue involving a login for a site. I was able to use the information here to enable a post back from a http page to a https page thus solving my requirement for secure login without making the whole page https. And with a bit of luck i wont get the mixed content message, but have to test for that.
 
Big Grin | :-D
 
Thanks again.
 
Dave
GeneralBRILLIANT !!!memberdavidhart31 Oct '07 - 5:37 
thank you!
GeneralPostBackUrlmembersharky1916 Aug '07 - 3:52 
why not use the PostBackUrl for posting to another aspx page?????
GeneralRe: PostBackUrlmemberDavid Truxall20 Aug '07 - 1:36 
There is no PostBackUrl feature in .Net 1.1. The article was written in 2003.
GeneralRe: PostBackUrlmembersharky1920 Aug '07 - 2:34 
sorry,i didn't pay attention to the date.
have a nice day.

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

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