What is a simple way to count in C# how many times an asp net button has been clicked in the same page e.g page1.aspx? The counter should be valid per user and reset when I go to page2.aspx, then return back to page1.aspx. the counter should persist in case of reloading the same page.
the button is created dynamically in Page Init
Button x = new Button();
I cannot use javascript. thanks
Create a class for maintain hit counters
public static class Counter
{
private static long hit;
public static void HitCounter()
{
hit++;
}
public static long GetCounter()
{
return hit;
}
}
Increment the value of counter at page load event
protected void Page_Load(object sender, EventArgs e)
{
Counter.HitCounter(); // call static function of static class Counter to increment the counter value
}
the time you redirect the user you can make count as null
The better way to use session, it enables you to store and retrieve values for a user as the user navigates ASP.NET pages in a Web application. So that you can access the value even when you returning from page2.aspx. the code for this will be
protected void button_Click(object sender, EventArgs e)
{
if(Session["ClickCount"]!=null)
Session["ClickCount"]=(int)Session["ClickCount"]++;
else
Session["ClickCount"]=0;
}
If you want to reset it when you leave the page means you can use:
if(Session["ClickCount"]!=null)
Session["ClickCount"]=0;
// Redirect to page
Related
From the selectedindexchanged event, my variable has a value, but when it reaches the btn_click() event, the variable no longer has a value. Why is that?
public partial class TestingDatapass
{
private string item = null;
private string itemprice = null;
private int totalprice = 0;
protected void item_selectedindexchanged(object sender, EventArgs e)
{
//Both have a value here
item = item.SelectedValue;
itemprice = item.SelectedValue.Text;
}
protected void btn_click(object sender, EventArgs e)
{
//no value here
totalprice = Convert.ToInt32(itemprice)*Convert.ToInt32(item);
MessageBox.Show(totalprice);
}
}
EDIT
And to answer the ? posed in comments, the order of occurrence is the selectedindexchange THEN the btn_click()
EDIT REGARDING View State
So then would this be a proper way to set up what I am trying to achieve?
public partial class TestingDatapass
{
private int totalprice = 0;
protected void item_selectedindexchanged(object sender, EventArgs e)
{
ViewState["item"] = item.SelectedValue;
ViewState["itemprice"] = item.SelectedValue.Text;
}
protected void btn_click(object sender, EventArgs e)
{
totalprice = Convert.ToInt32(ViewState["item"])*Convert.ToInt32(ViewState["itemprice"]);
}
}
When a page is requested, ASP.NET creates an instance of TestingDatapass class and initialize itemprice,totalprice etc. fields. Now when you change your dropdown from client (which I assume looking at your item_selectedindexchanged method), Postback happens and it assign values you have mentioned in item_selectedindexchanged. Finally it destroys the instance, generates the html and sends it back to browser.
Now, when you press the button in your page then a new instance is created, your fields are re-initialized and you don't see the changed values in btn_click. This is how it works.
Thus if you want to preserve any data across postback, Consider using any State Management technique like ViewState, HiddenField etc.
Also, as a side note, MessageBox.Show is not available in ASP.NET.
Update:
I answered in the context of why it is not retaining the value in button click event, there are many ways to do it. But to answer your question, I don't see any reason to store the values in item_selectedindexchanged event as you are not doing anything there. You can directly access the dropdown selected values in button click handler like this:-
protected void btn_click(object sender, EventArgs e)
{
totalprice = Convert.ToInt32(item.SelectedValue) *
Convert.ToInt32(item.SelectedItem.Text);
}
Also, please note it's item.SelectedItem.Text and not SelectedValue.Text.
In "edmx" page I have button control with event "NextButton_Click" for click. When I click this button the variables "index" doesn't want to change to "40" and the "text"
variable doesn't want to change to "active". These variables are always in the same state "text" is always equal to "start" and "index" is always equal to "10". Why they don't want to change with (index = 40;
text = "active";) as I wrote in the click button event method ?
public partial class CountriesTowns : System.Web.UI.Page
{
int index = 10;
string text = "start";
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
index = 20;
text = "stop";
}
}
//click next button
protected void NextButton_Click(object sender, EventArgs e)
{
Response.Write(index);
Response.Write(text);
index = 40;
text = "active";
}
HTTP is stateless, every object like your index or text(and even all controls) are destroyed at the end of the page's life-cycle. So they are always initialized with their default value.
int index = 10;
string text = "start";
You can use a control(f.e. a TextBox or a HiddenField) to persist their value across postbacks.
But there are other options:
Nine Options for Managing Persistent User State in Your ASP.NET Application
You are not persisting the updated state of the index and text variables between post backs. As such, since a new instance of CountriesTowns is created per request, the values are re-initialised to their default values.
Every time you click a button, you cause what is known as a Postback. A Postback does not just run your click code... it also rebuilds your entire page. To do this, it creates a brand new instance of your Page class, which is then destroyed as soon as the html for your new page is completed. It has to do this because the original instance of your Page class was also destroyed as soon the html was rendered.
How can I put variables that have scope the whole session on ASP.NET Page (I mean in the class that stands behind the aspx page)? Is the only way to put the variable in the Session object?
For example:
public partial class Test_ : System.Web.UI.Page
{
private int idx = 0;
protected void Button1_Click(object sender, EventArgs e)
{
Button1.Text = (idx++).ToString();
}
}
I want on every click on this button my index to go up. How can I do this without using the Session object?
You can put it in ViewState instead
public partial class Test_ : System.Web.UI.Page {
protected void Button1_Click(object sender, EventArgs e) {
if(ViewState["idx"] == null) {
ViewState["idx"] = 0;
}
int idx = Convert.ToInt32(ViewState["idx"]);
Button1.Text = (idx++).ToString();
ViewState["idx"] = idx;
}
}
ViewState seems to be what you're looking for here, so long as that counter doesn't need to be maintained outside the scope of this page. Keep in mind that a page refresh will reset the counter though. Also, if the counter is sensitive information, be wary that it will be stored (encrypted) in the rendered HTML whereas Session values are stored server-side.
There are a number of options besides the session. Take a look at Nine Options for Managing Persistent User State in Your ASP.NET Application.
For this sort of data, you probably would want use the session store.
Is it recommended to check the Page.IsPostBack in a user control Page_Load Event like
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
}
I am getting wierd results
Edit ~ Here is the thing. When the main form is loaded, I use Request.QueryString to get the customer id which I then place in a SESSION variable.
On the control Load event I read the SESSION variable to get the data for that customer. So, do I need to check PostBack at the control level?
Edit ~ Here is the load event of the control
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//Getting and storing the customer account number
if (string.IsNullOrEmpty((string)Session["CustomerNumber"]))
{
Session["CustomerNumber"] = cust.GetCustomerNumber(myHelper.GetCustomerIDFromQueryString());
LoadProductData();
}
}
}
Here is the myHelper Class
static class myHelper
{
public static Guid GetCustomerIDFromQueryString()
{
//Getting the GUID (used as customerid in CRM) from the URL request of the selected account.
return Sql.ToGuid(System.Web.HttpContext.Current.Request["ID"]);
}
}
}
If you use "!IsPostBack" in page load, when the user click other control it do a postBack, so you don't get your data.
I hope that helps you.
Just checking it for no reason? Absolutely not. If you should do something only on first load and not on subsequent post backs then it's the pattern that should be used.
Are you sure that you will always have a "CustomerNumber" already stored in the Session by the time you get to your page? Is there any rhyme or reason that you can find as to when you get data and when you don't?
How do I increment a step value to be processed when the page loads? For example, in the code below the viewstate variable is not incremented until after Page_Load, due to the ASP.NET page lifecycle.
protected void Page_Load(object sender, EventArgs e)
{
switch ((int)ViewState["step"])
{
//do something different for each step
}
}
protected void btnIncrementStep_Click(object sender, EventArgs e)
{
//when the button is clicked, this does not fire
//until after page_load finishes
ViewState["step"] = (int)ViewState["step"] + 1;
}
Just move the switch statement into an event that happens later. E.g. LoadComplete() or PreRender(). PreRender is probably a bit late, depending on what you want to do.
There's no way around this. Page_Load event will always happen before any control events get fired. If you need to do something after the control event, use Page_PreRender.
ASP.Net Page Lifecycle Image
Increment during the LoadComplete event or even during OnLoad.
You have all the information needed to make the decision whether to increment from the form data. You don't need to wait for the onClick() event. Check the form to see if the item will be clicked.
Look in the request.params("__EVENTARGS")
This identifies the control that caused the postback.
If you need to increment and check the value during Page_Load, then an option would be to store the value in the session instead of ViewState, e.g:
private int Step
{
get { return (int)Session["step"]; }
set { Session["step"] = value; }
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
Step = 0; // init
else
Step ++; // increment
switch (Step)
{
//do something different for each step
}
}