tags:

views:

979

answers:

4

can any one explain how to transfer a variable between asp pages by web request. Web request means post method and also suggest a best method in asp for transfering variable between the asp.net pages

A: 

What do you mean by web request?

You can post it to another page using web request.

string myvar = "abc";
WebRequest request = WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
using(Stream writeStream = request.GetRequestStream())
{
    UTF8Encoding encoding = new UTF8Encoding();
    byte[] bytes = encoding.GetBytes("myvar=" + myvar);
    writeStream.Write(bytes, 0, bytes.Length);
}

And retrieve it there using

string myvar = Request.Post["myvar"];

But may be you should consider other options?

You can transfer it using Session or Application objects.

You can transfer it by query string.

Alex Reitbort
what i mean by web request is post method only. Also suggest which method is best for asp.
Ksmps
+1  A: 

have a look at System.Net.WebClient.UploadString() or System.Net.WebClient.UploadValues()

flesh
+3  A: 

There are a number of ways that you can pass variables between ASP.NET pages-

  1. In Session State
  2. In Query String
  3. Reading Values from the source page (exposed as properties)

MSDN article - How to Pass Values between ASP.NET pages

I have never had the need to use HttpWebRequest to pass values between pages. As I understand it, this was a standard method of passing values in Classic ASP. Whilst you can still use this method in ASP.NET (as demonstrated by Alex's answer), I think you will find one of the method's above more concise and one to fit different purposes.

Russ Cam
+1  A: 

You have some alternatives, you can use the query string, the session, using Server.Transfer and the HttpContext.

You can do Cross-Page Postbacks and the last page is exposed by the PreviousPage property...

CMS
The only downside that I have found with Cross Page Postbacks is to do with Server Side validation - the validation check is carried out on the page that is cross posted back to! I haven't seen a way around this
Russ Cam