Interacting With Get and Post Methods in ASP.NET
Posted by triaslama on May 1, 2008
There are two common ways to pass data from one page to another, using http Get and Post methods. In Get method, data passed to server using URL encoding. So with Get method data added in URL as query string. For more information on how to retrieve query string values, you can read my previous post here. When we use Post method the URL is still intact, because data passed in HTTP body.
In correlation with ASP.NET, retrieving data passed through HTTP Get and Post methods is quite simple. If data passed with Get method we need the following code to retrieve the data:
If data passed with Post method we need the following code to retrieve the data:
Maybe the problem will more suitable addressed with hand in code practice, so let’s try a simple code! I named the HTML file as methods_source.htm:
Methods_source.htm consists of two HTML forms. First form will pass data within it using GET method, and second form will pass data within it using POST method.
When we click submit button of first form, we will be redirected to get_recv.aspx (as stated in action attribute) in a new window. Click the submit button of second form will bring us to post_recv.aspx (opened in new window too). This is screenshots of our page:
The name and address text boxes of first form will be sent as parameter of query string with the field name are name and addr respectively. The name of query string fields automatically taken from name attribute of each HTML element, so don’t forget to specify the name attribute to make it works! Inside get_recv.aspx we retrieve the query string values using Page.Request.QueryString[“name”] and Page.Request.QueryString[“addr”]. Here get_recv.aspx:
When I fill name & address textboxes with ‘Muadz’ and ‘Senayan City, Jakarta’ respectively and click the ‘Send Using Get’ button I get the following URL: http:…/getpost/get_recv.aspx?name=Muadz&addr=Senayan+City%2C+Jakarta. The data from methods_source.htm will be showed in tabular format, so this is what we get:
Get_recv.aspx, name and address values taken from query string.
Values of second form sent using POST method therefore the URL still intact, we retrieve name 2 and address 2 using Page.Request.Form[<param>], <param> value taken from the name each of HTML element of second form (Once again don’t forget specify name attribute for name 2 and address 2 textboxes to make it works!). When ‘Send Using Post’ button clicked, values of second form passed to post_recv.aspx. This is code for post_recv.aspx:
This is screenshots of post_recv.aspx when I fill name 2 and address 2 with ‘Ali’ and ‘Wirogunan, Yogyakarta’ respectively:
Data sent using POST method received by post_recv.aspx and showed in tabular format.