How should i use the "PostBack"? - c#

Clarification: I am chilean, so my english is not perfect, sorry for the misspellings.
Hi, I am working with an image in c#.
I try to put an example image when the page open the first time, I used the post back for this, but when I press a button, execute the code in the post back section (which is right), after that it execute the Button code, but then, it pass again for the Page_Load method, and execute the "not post back" section, and i dont know why.
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
//Is post back
}
else // Is not post back
{
//Make things only when the page is open for the first time
}
}

I usually only use (!IsPostBack) on PageLoad for doing initial data loads or validations(like settings for users).
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (userIsAdmin)
{
button1.Enabled = true;
}
}
}
You could refer to the link for the explanation for PostBack https://learn.microsoft.com/en-us/dotnet/api/system.web.ui.page.ispostback?view=netframework-4.8

Related

asp.net Load Child page only from parent page

I have two pages MainPage.aspx and ChildPage.aspx. From main page when i click a button i redirect to ChildPage.
If i give the address of ChildPage directly on browser, i do not want to load it directly instead i want to redirect to MainPage.
the ChildPage must be loaded only if it is loaded from the MainPage.
How do I find from where the ChildPage.aspx is loaded. how to find the parent page of it or from where it is loaded.
can we try something in the below code
if (!IsPostBack)
{
if (finding_source)
{
Response.Redirect("MainPage.aspx");
}
}
You can use Request.UrlReferrer.AbsolutePath to see the previous page.
if (!IsPostBack)
{
if (Request.UrlReferrer != null && Request.UrlReferrer.AbsolutePath == "/MainPage")
{
//do what you want
}else{
Response.Redirect("~/MainPage.aspx");
}
}
TIP But be careful with using it with postbacks since it will change the value of Request.UrlReferrer to the current page during a postback.
Even though your question is not clear , here i am trying to give my solution.
MAINPAGE.ASPX BUtton Click
protected void lnkRegister_Click(object sender, EventArgs e)
{
Session["MainPage"] = "true";//Encrypt it if u wish
Response.Redirect("childpage.aspx");
}
CHILDPAGE.ASPX PAGE LOAD
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
if (!string.IsNullOrEmpty(Session["MainPage"] as string) && Session["MainPage"].Tostring()=="true")
{
//proceed
}
else
{
Response.Redirect("mainpage.aspx");
}
}
GLOBAL.ASAX
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
Session.RemoveAll();
Session.Clear();
Response.Cache.SetExpires(DateTime.UtcNow.AddDays(-1));
Response.Cache.SetValidUntilExpires(false);
Response.Cache.SetRevalidation(HttpCacheRevalidation.AllCaches);
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
}
it is little difficult to control browser shutdown or close...but you can workaround global asax file when your application shutsdown.

ViewState value not being retained during postback

How can I make this piece of code work? I am dealing with a bigger issue but if I can make this work then I will know what to do.
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
Response.Write(ViewState["Value"].ToString());
}
}
protected void Button1_Click(object sender, EventArgs e)
{
ViewState["Value"] = "Button clicked";
}
Page_Load event happens before Button1_Click and hence you wont be able to access a value that is not already set.
You will need to use an event that happens after Button1_Click like Page_PreRender as you have used in the answer.
Please go through this link to understand Page Life Cycle, which is invaluable in Asp.Net Webforms development.
I was able to solve my problem by putting my logic in pageLoad method in the page_PreRender method like this:
protected void Page_PreRender(object sender,EventArgs e)
{
if (IsPostBack)
{
Response.Write(ViewState["Value"].ToString());
}
}

C# how to stop a control's event

I have an .aspx page that has a page_load as follows:
protected void Page_Load(object sender, EventArgs e)
{
if (HttpContext.Current.User.Identity.Name != "")
{
....
}
else
{
FormsAuthentication.RedirectToLoginPage();
return;
}
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
....
}
The issue I am noticing is that when the user clicks the submit button it goes though the Page_Load (goes though the else) and then tries to run though the protected void btnSubmit_Click(object sender, EventArgs e).
Is there a way to make it redirect to the login page and not continue to the next void?
This is NOT an issue. This is the normal ASP.NET Page Life Cycle.
Controls events fire right after the Page_Load event.
Note that the FormsAuthentication.RedirectToLoginPage method does not end the request by calling HttpResponse.End. This means that code that follows the RedirectToLoginPage method call will run.
Assuming you want to stop further processing from within the Page_Load (which I believe is your intention with return):
protected void Page_Load(Object sender, EventArgs e)
{
if (/*I want to kill processing*/)
{
// Method one:
Response.End(); // Though admittedly ugly
// Method two:
this.Context.ApplicationInstance.CompleteRequest();
return; // return as normal (short-circuit)
}
}

Only add items to a dropdown list once

I have a dropdown list that is populated when the page loads, like this:
protected void Page_Load(object sender, EventArgs e)
{
ddlCars.Items.Add("Ford");
ddlCars.Items.Add("Chevy");
ddlCars.Items.Add("BMW");
ddlCars.Items.Add("Jeep");
ddlCars.Items.Add("Nissan");
}
It works fine, but when a user changes the selection of the dropdown list, the list is repopulated and I see the same items twice, because the page is reloading and these values are being re-added.
What would be the best way to stop this from happening? It is important that AutoPostBack stays enabled, so that I change information based on user selection.
Thanks
You need to put that code in a !Page.IsPostBack block.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ddlCars.Items.Add("Ford");
ddlCars.Items.Add("Chevy");
ddlCars.Items.Add("BMW");
ddlCars.Items.Add("Jeep");
ddlCars.Items.Add("Nissan");
}
}
This will allow that code to run once (when the page loads the first time), and then be ignored whenever the page is posting back to the server due to user interaction, etc.
For more information, see Page.IsPostBack on MSDN.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack) {
ddlCars.Items.Add("Ford");
ddlCars.Items.Add("Chevy");
ddlCars.Items.Add("BMW");
ddlCars.Items.Add("Jeep");
ddlCars.Items.Add("Nissan");
//ddlCars.datasource=?
//ddlCars.databind();
}
}

What is the best way to distinguish beteen "Refresh Post" or a "Real Post Back"

What is the best way to distinguish beteen "Refresh Post" or a "Real Post Back".
This is what I need to attain
protected void Button1_Click(object sender, EventArgs e)
{
if(PostBack && !Refresh)
{
//Do Something
}
}
I usually do a Response.Redirect to the same page in the postback event.
That way all my Page.IsPostBack are real Postbacks and not Refreshes
You could set a hidden input with a nonce value generated randomly every time the form is loaded (but not on postback), then check if the nonce value got sent twice. If it got sent a second time, it was a refresh.
you could try like
protected void Button1_Click(object sender, EventArgs e)
{
//your code of Click event
//..............
//...............
// and then add this statement at the end
Response.Redirect(Request.RawUrl); // Can you test and let me know your findings
}
Sample working code for the accepted answer
Add this line in designer
<input type="hidden" runat="server" id="Tics1" value="GGG" />
Add following lined in the code behind
public partial class WebForm1 : System.Web.UI.Page
{
long tics = DateTime.Now.Ticks;
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.Tics1.Value = tics.ToString();
Session["Tics"] = tics;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Session["Tics"] != null && Request["Tics1"] != null)
{
if (Session["Tics"].ToString().Equals((Request["Tics1"].ToString())))
{
Response.Write("Postback");
}
else
{
Response.Write("Refresh");
}
}
this.Tics1.Value = tics.ToString();
Session["Tics"] = tics;
}
}

Categories