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.
Related
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
I'm making a web app in Asp.Net using c# that lets you add items into the list.
My problem is that each time that i click the button to add a new item into the list , its just shows me the last item and the list counter shows me only 1 .
What am I doing wrong??
Here is the code :
public partial class home : System.Web.UI.Page
{
List<string> messageboxs = new List<string>();
public string val = "";
public string data = "";
protected void Button1_Click(object sender, EventArgs e)
{
val = "";
messageboxs.Add(text1.Text);
ListBox1.DataSource = messageboxs;
ListBox1.DataBind();
val = messageboxs.Count.ToString();
}
}
Your list is not persisted between postbacks.
Every time you click a button a new instance of the page class and therefore list is created. This list is empty.
You should read up on ASP.NET Page Life Cycle Overview. In a nut shell, everytime you click the button it causes the page to postback which creates a new instance of the page. You are initializing an empty list on each instance of that page therefore when you come to adding the new item into the list...it's empty again.
What you need to do is store messageboxs somewhere which will allow it to persist across postbacks. For your particular example, you could use the ViewState e.g.
public partial class home : System.Web.UI.Page
{
private void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
// initialise list
ViewState["Messages"] = new List<string>();
}
}
protected void Button1_Click(object sender, EventArgs e)
{
// get the old messages list
var messages = (List<string>)ViewState["Messages"];
messages.Add(text1.Text);
ListBox1.DataSource = messages;
ListBox1.DataBind();
// store the new messages list
ViewState["Messages"] = messages;
}
}
The problem is in how ASP.Net works. ASP.Net is recreating your "home" page on each button click. This then recreates the list, and you add one item to it. You need a way to save the list between button clicks. That's what, for example, the Session is for.
The list is created again on each postback. You should look at going through the existing items in ListBox1 and re-adding them to your List<string> then re-binding.
Make your messageboxs static variable as
static List messageboxs = new List();
But this makes the variable accessible from any page request.
meaning if someone else open this page and tried to add an item he/she will end up adding an item to someone else's list.
try using session state or view state instead.
I try to create a web application that got a button that change an image. this is my code:
public partial class _Default : System.Web.UI.Page
{
private bool test ;
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
if (test)
{
Image1.ImageUrl = #"~/images/il_570xN.183385863.jpg";
test = false;
}else
{
Image1.ImageUrl = #"~/images/BAG.png";
test = true;
}
}
}
my problem is that the page reload every time. meaning, after i click the button "test" return to it's initial value. how can i have a variable that i can access all through the session?
please notice, i don't want to solve this specific image problem, but to know how to keep data until the user closed the page.
You can store arbitrary values in Session
Session["someKey1"] = "My Special Value";
Session["someKey2"] = 34;
Or more complex values:
Session["myObjKey"] = new MyAwesomeObject();
And to get them back out:
var myStr = Session["someKey1"] as String;
var myInt = Session["someKey2"] as Int32?;
var myObj = Session["myObjKey"] as MyAwesomeObject;
ASP.NET webforms are stateless so this is by design.
you can store your bool variable in the ViewState of the page so you will always have it updated and persisted within the same page.
Session would also work but I would put this local page related variable in the ViewState as it will be used only in this page ( I guess )
Store the variable in a cookie! :)
Example:
var yourCookie = new HttpCookie("test", true);
Response.Cookies.Add(yourCookie);
Session["show_image"] = "true";
To achieve what you want you need to check if is PostBack or not as so:
protected void Button1_Click(object sender, EventArgs e)
{
if (test && !IsPostBack)
{
Image1.ImageUrl = #"~/images/il_570xN.183385863.jpg";
test = false;
}else
{
Image1.ImageUrl = #"~/images/BAG.png";
test = true;
}
}
BUT, don't do it that way. You are approaching this wrong. You wouldn't want to store in Session things like whether this image is shown or not, etc. It's difficult to suggest an approach without knowing the specific issue you are facing.
Another option than the already mentioned would be to store the data in the ViewState. If it's just used in postback situations, that might be a possible way.
ViewState["test"] = true;
You save memory on the server but use a little bit of bandwith. The data gets lost, when the user browses to another page.
i want to pass a string value from one page to another.Also i have some text boxes and the values entered in it needs to be passed to a new page.How do i do it?
I have a string S
String S = Editor1.Content.ToString();
i want to pass value in string S onto a new page i.e Default2.aspx how can i do this in ASP.net C#
You can achieve it using Session or by QueryString
By Session
In your first page:
String S = Editor1.Content.ToString();
Session["Editor"] = S;
Then in your next page access the session using:
protected void Page_Load(object sender, EventArgs e)
{
String editor = String.Empty;
if(!String.IsNullOrEmpty(Session["Editor"].ToString()))
{
editor = Session["Editor"].ToString();
// do Something();
}
else
{
// do Something();
}
}
-
By QueryString
In your first page:
// or other events
private void button1_Click(object sender, EventArgs e)
{
String S = Editor1.Content.ToString();
Response.Redirect("SecondPage.aspx?editor" + S)
}
In your second page:
protected void Page_Load(object sender, EventArgs e)
{
string editor = Request.QueryString["editor"].ToString();
// do Something();
}
Depends on what the value is. If it is just a parameter and is ok to be viewed by the user then it can be passed through QueryString.
e.g.
Response.Redirect("Default2.aspx?s=value")
And then accessed from the Default2 page like
string s = Request.QueryString["s"];
If it needs to be more secure then consider using session, but I wouldn't recommend using the Session excessively as it can have issues, especially if you are storing the session InProc which is ASP.NET default.
You can have a state server or database but, it might be better to have your own database based session based on the authenticated user, and have it cached in the website if need be.
Use Session["content"]=Editor1.Content.ToString() in page1...
in page2 use...string s = Session["content"]
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?