ASP.net passing data between pages - asp.net

I have a .aspx web page, with a html form within it, this also has two input boxes.
Whats the best way to take the input box data and pass it to a new .aspx page where it is dealt with by the request method.

Assuming that the data is not sensitive then the best method to pass it to your new page using Response.Redirect and the querystring using:
protected void MyFormSubmitButton_Click(Object sender, EventArgs e)
{
string value1 = txtValue1.Text;
string value2 = txtValue2.Text;
// create a querystring
string queryString = "x=" + value1 + "&y=" + value2;
// redirect to the encoded querystring
Response.Redirect("NewPage.aspx?" + Server.URLEncode(queryString));
}

This web page has a lot of information which you can use for passing the values from page to page.
http://msdn.microsoft.com/en-us/library/6c3yckfw.aspx#Y1100

Try Server.Transfer:
Terminates execution of the current
page and starts execution of a new
page by using the specified URL path
of the page. Specifies whether to
clear the QueryString and Form
collections.
If you set the preserveForm parameter
to true, the target page will be able
to access the view state of the
previous page by using the
PreviousPage property.
Your main page:
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
// ThreadAbortException occurs here.
// See http://support.microsoft.com/kb/312629 for more details.
Server.Transfer("AnotherPage.aspx", true);
}
}
"AnotherPage.aspx":
protected void Page_Load(object sender, EventArgs e)
{
if (PreviousPage != null)
{
// Accessing previous page's controls
}
}

Related

Query String values not related to Active Forums don't survive the PostBack

Query String values not related to Active Forums don't survive the PostBack.
Example URL (before submit): http://www.example.com/activity/afv/post/aff/279/aft/20/afr/20/groupid/797?versiontest=123
URL (after submit): http://www.example.com/activity/aft/20/groupid/797#33 (versiontest parameter is missing).
How can I keep these query string parameters after postback?
You can try setting the form's action to the raw url.
protected void Page_Load(object sender, EventArgs e)
{
form1.Action = Request.RawUrl;
}

.net using and reaching public value

I wrote this code in .NET. When I want to change ‘s’ by clicking button2, it doesn’t change. I mean after clicking button2 and then I click Button1 to see the changes but nothing changes. How can I change and access the value of ‘s’ properly. What am I doing wrong?
public string s;
public void Button1_Click(object sender, EventArgs e)
{
Label1.Text = s;
}
public void Button2_Click(object sender, EventArgs e)
{
s = TextBox1.Text;
}
You need to understand how web applications work.
In each post back an instance of the class that handles the page is loaded, so when you click on button 1, the page does a post back and loads again, so this way the variable s isn't loaded with your content.
To make this code work, you need to save the S values on the page viewstate.
try replacing "public string s;" with this:
public string s
{
get { return (string)ViewState["myValue"]; }
set [ ViewState["myValue"] = value };
}
More Information about Page Life Cycle at: http://msdn.microsoft.com/en-us/library/ms178472(v=vs.100).aspx

User input is overridden by page_load during cross page postback

1the source page has a page load method like below:
protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Text = DateTime.Today.AddDays(1).ToShortDateString();
}
it will result a textbox1.text to display tomorrow's date when the source page is rendered. I have this source page cross post back to a target page, and in the target page load event i have
if (Page.PreviousPage != null && PreviousPage.IsCrossPagePostBack == true)
{
TextBox SourceTextBox1 = (TextBox)Page.PreviousPage.FindControl("TextBox1");
if (SourceTextBox1 != null)
{
Label1.Text = SourceTextBox1.Text;
}
}
the problem is if the user changes the content of textbox1, supposely, the label1 on target page should catch the user input and display it, but now it only displays whatever i set in the source page load event. I understand the self page post back life cycle, but this is cross page post back. IMO, the source page load event has nothing to do with this, but why it overrides the user input?? Any idea.
Just surround this with a if(!IsPostBack) check:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
TextBox1.Text = DateTime.Today.AddDays(1).ToShortDateString();
}
}
Otherwise the value will be overwritten on every postback. So when you Server.Transfer it to the other page it is already changed.

Prevent Page Refresh in C#

Duplicate of Asp.Net Button Event on refresh fires again??? GUID?
hello, ive a website and when a user click a button and the page postback, if the user refresh the Page or hit F5 the button method is called again.
any one know some method to prevent page refresh with out redirect the page to the same page again ?
something like if (page.isRefresh) or something... or if exist any javascript solution is better.
this seen to works.... but when i refresh it does not postback but show the before value in the textbox
http://www.dotnetspider.com/resources/4040-IsPageRefresh-ASP-NET.aspx
private Boolean IsPageRefresh = false;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
ViewState["postids"] = System.Guid.NewGuid().ToString();
Session["postid"] = ViewState["postids"].ToString();
TextBox1.Text = "Hi";
}
else
{
if (ViewState["postids"].ToString() != Session["postid"].ToString())
{
IsPageRefresh = true;
}
Session["postid"] = System.Guid.NewGuid().ToString();
ViewState["postids"] = Session["postid"];
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (!IsPageRefresh) // check that page is not refreshed by browser.
{
TextBox2.Text = TextBox1.Text + "#";
}
}
Thanks for comments and sorry for my mistake,
I found this code in:
http://www.codeproject.com/KB/aspnet/Detecting_Refresh.aspx
And this time tested ;)
private bool _refreshState;
private bool _isRefresh;
protected override void LoadViewState(object savedState)
{
object[] AllStates = (object[])savedState;
base.LoadViewState(AllStates[0]);
_refreshState = bool.Parse(AllStates[1].ToString());
_isRefresh = _refreshState == bool.Parse(Session["__ISREFRESH"].ToString());
}
protected override object SaveViewState()
{
Session["__ISREFRESH"] = _refreshState;
object[] AllStates = new object[2];
AllStates[0] = base.SaveViewState();
AllStates[1] = !(_refreshState);
return AllStates;
}
protected void btn_Click(object sender, EventArgs e)
{
if (!_isRefresh)
Response.Write(DateTime.Now.Millisecond.ToString());
}
You can test for the Page.IsPostBack property to see if the page is responding to an initial request or if it's handling a PostBack such as your button click event. Here's a bit more information: w3schools on IsPostBack
Unfortunately that's not going to solve your problem since IsPostBack will be true when the user clicks the button as well as when they refresh the page after the button action has taken place.
If you're doing a task like performing CRUD on some data, you can Response.Redirect the user back to the same page when you're done processing and get around this problem. It has the side benefit of reloading your content (assuming you added a record to the DB it would now show in the page...) and prevents the refresh problem behavior. The only caveat is they still resubmit the form by going back in their history.
Postbacks were a bad implementation choice for the Asp.net and generally are what ruin the Webforms platform for me.
This doesn't solve the problem.
First of all, storing a token in the view state is not a good idea, since it can be disabled. Use control state instead. Although, a HttpModule is a better solution.
All in all, this will not work anyway. If you open another tab/window the session will be invalid for the previous tab/window. Therefore braking it. You must somehow store a unique value each time a page is first loaded. Use that to determine where the request came from and then check the "refresh ticket". As you may see, the object for one user might get pretty big depending on the amount of requests made, where and how long you store this information.
I haven't seen any solution to this I'm afraid, as it is pretty complex.
bool IsPageRefresh ;
if (Page.IsPostBack)
{
if (ViewState["postid"].ToString() != Session["postid"].ToString())
IsPageRefresh = true;
}
Session["postid"] = System.Guid.NewGuid().ToString();
ViewState["postid"] = Session["postid"];
I tried many ways and I ended up looking for the form data sent when the postback / refresh is triggered... I found that there is a Key for any VIEWSTATE created and you can just compare those Keys like...
I put that on my custom basepage to reuse it like an Property
public bool IsPageRefresh = false;
protected void Page_Init(object sender, EventArgs e)
{
if (IsPostBack)
{
var rForm = Request.Form;
var vw = rForm["__EVENTVALIDATION"].ToString();
var svw = Session["__EVENTVALIDATION"] ?? "";
if (vw.Equals(svw)) IsPageRefresh = true;
Session["__EVENTVALIDATION"] = vw;
}
}

Accessing Events And Members In The Master Page

I have an event in the Master page that I want to access in the pages that use that master page but it doesn't seem to be working.
In the Master
public delegate void NotifyRequest(object sender, EventArgs e);
public class MyMaster
{
public event NotifyRequest NewRequest;
protected void uiBtnNewTask_Click(object sender, EventArgs e)
{
if(NewRequest!= null)
NewRequest(this, e)
}
}
Inherited Page
MyMaster mm = new MyyMaster();
mm.NewRequest += new NotifyRequest(mm_NotifyRequest);
void mm_NotifyRequest(object sender, EventArgs e)
{
Label1.Text = "Wow";
this.Label1.Visible = true;
}
My problem is the event is always null. Any ideas?
You probably need to use the following syntax to access your event in the Master Page
((MyMaster)Master).NewRequest += new NotifyRequest(mm_NotifyRequest);
If you wish to access members of a master page you need to use the page Master attribute and cast it to your master page.
Alternately
If you wish do not wish to use a cast you can use the #MasterType directive to create a strong reference to your master page, in this case MyMaster. So you would be able to access your event like so: Master.NewRequest.
More Reading about Master Pages

Resources