Page Reload - Keeping Variables - c#

How do I go about when page is reloaded that I make sure the variables I have declared at the top o my class do not get reset. IE I have a counter that is originally set at 0 if I use a postback control it resets that variable how do i go about not having this happen in C#?

Are you looking for a value specific to the client or to the server?
If you want something specific to the client use a cookie or session value.
If you are looking something specific to the server use a static class, application or cache value.

Use ASP.Net Session or Cookies. Or you can store their values in hidden fields. You can read about theese and outher option in following article.

Put the value you want to save in a cookie.

if you´re using a postback, not a link, you should save your data into viewstate.
vb
Public Property MyValue() As String
Get
Dim _mv As Object = ViewState("MyValue")
If Not _mv Is Nothing Then
Return _mv.ToString
End If
Return String.Empty
End Get
Set(ByVal value As String)
ViewState("MyValue") = value
End Set
End Property
C#
public string MyValue {
get {
object _mv = ViewState("MyValue");
if ((_mv != null)) {
return _mv.ToString();
}
return string.Empty;
}
set { ViewState("MyValue") = value; }
}
ViewState is saved along PostBacks, if you stay on the current page. For Example if you are on page.aspx and using a <asp:button> that is clicked each time, you can use Viewstate as a place for saving some of your data, it looks in the page source code like this
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwULLTE4Mzg3MjEyMzdkZNNlI9zvMeIGeUB4MZbJA2gmsHns9IsmAy/c4dQMybXD" />
the viewstate is generated automatically

That data is not persisted on HTTP Requests; you need to persist it in a cookie, hidden control, or manually store it in view state.
If you're manually doing a page counter, consider storing it in session state.

Related

ASP.Net Static Value keep accumulate while refreshing the page

I have an asp.net page, and a static value totalBalance that sums the values in a column in a gridview.
I found, when I refresh the page, the totalBalance get accumulated instead of keep the original value.
Is there any code I could insert so that it can refresh the values, and each time I refresh the page, it is re-calculating the column values instead of accumulating numbers?
I currently have this RemoveCache
protected void RemoveCache()
{
Response.CacheControl = "no-cache";
Response.AddHeader("Pragma", "no-cache");
Response.Expires = -1;
}
Can I insert some code in this or the aspx to reset the value after running please?
Thanks.
Never mind, I set totalBalance=0 when loading the page....
A static variable is a variable that has one copy of it (which means shared throughout the application) and its lifetime is the same as the application, once instantiated. Regardless of refresh, the variable is the same one from the first time it was created and you are re-using and re-totaling a running value. I would say stop using static variables in your web applications unless you really understand the implications and the problem should go away.

How to remove specific session in asp.net?

I am facing a problem. I have created two sessions:
Session["userid"] = UserTbl.userid;
Session["userType"] = UserTbl.type;
I know how to remove sessions using Session.clear(). I want to remove the session "userType".
How do I remove a specific session?
Session.Remove("name of your session here");
There is nothing like session container , so you can set it as null
but rather you can set individual session element as null or ""
like Session["userid"] = null;
you can use Session.Remove() method; Session.Remove
Session.Remove("yourSessionName");
There are many ways to nullify session in ASP.NET. Session in essence is a cookie, set on client's browser and in ASP.NET, its name is usually ASP.NET_SessionId. So, theoretically if you delete that cookie (which in terms of browser means that you set its expiration date to some date in past, because cookies can't be deleted by developers), then you loose the session in server. Another way as you said is to use Session.Clear() method. But the best way is to set another irrelevant object (usually null value) in the session in correspondance to a key. For example, to nullify Session["FirstName"], simply set it to Session["FirstName"] = null.
HttpContext.Current.Session.Remove("sessionname");
it works for me
A single way to remove sessions is setting it to null;
Session["your_session"] = null;

How to get object in C# when it is dynamically created by javascript

I created several input text in Javascript in my .aspx
for (var i = 0; i < listbox.options.length; i++) {
var text = listbox.options[i].value;
var element = document.createElement("input");
//Assign different attributes to the element.
element.setAttribute("type", "text");
element.setAttribute("value", text);
element.setAttribute("id", "TMruleItem");
element.setAttribute("style", "width:480px; margin-top:10px");
element.setAttribute("disabled", "disabled");
element.setAttribute("runat","server");
var foo = document.getElementById("Panel_TM");
foo.appendChild(element);
}
However, when I try to get the text of this object in C#(code behind the .aspx), it seems impossible. Can anybody help with this? Thanks a lot!
The js runs client side AFTER the C# (server side) has rendered the page.
You cannot do what you want because you have fundamentally flawed model of how these technologies interact.
Having said that; you could implement a web service or ajax framework to pass the text value to the server.
I'm not exactly sure how you will add this into the C# side of things (which live on the server), because this element is only being added to the clientside (even if you add an attribute runat="server"), because the page that was generated has been sent.
However, if you need to be able to add elements dynamically, you could always pass some information using an ajax call (etc) that is stored somewhere (a database) that is then read to re-create the html element next time the page is generated...
End result though is that for the C# to be able to access the element, it must exist at some point on the server. If instead of accessing the element, you just want to access the value, provided the form is posted (ajax or regular) the value will be part of the Request variables:
string value = Request.Params["TMruleItem"];
Add the following to your javascript code:
element.setAttribute("name", "TMruleItem");
and entered values will be available on the server side:
string value = Request.Form["TMruleItem"];
I think you'd need to add the element to the form and when you post back to the server you can pull the value out using Request.Form

Accesing Server Control from other webform

I have 2 webforms with 1 ListBox Control on each of them.
How do I access the Listbox that's located on webformA from webformB?
For example I wish to declare something like this string name = ListBoxWebformA.SelectedValue.ToString(); on WebFormB, so that I can work with that value in the code of WebFormB.
The ListBox on WebFormA lists several names.
When I select a name from the listbox and press the OK button I call Response.Redirect("~/WebFormB.aspx");
So from WebFormB I wish to access this "name" by putting the selected value into a string.
Based on your edit, the easiest (possibly best) way to go about doing this will not be to try to maintain a stateful instance of webformA during the request to webformB. Once the user is redirected, assume that webformA is gone.
Instead, when you're about to perform the Response.Redirect() to webformB, include in some way the value from webformA that you wish to pass along. The easiest way to do this will be on the query string. Something like:
Response.Redirect(string.Format("~/WebFormB.aspx?name={0}", HttpUtility.UrlEncode(ListBoxWebformA.SelectedValue.ToString())));
Then, in webformB you can access the value:
string name = Request.QueryString["name"];
Note that you'll want to do some error checking, etc. Make sure the value is actually selected before appending it to the redirect URL on webformA, make sure Request.QueryString["name"] contains a value before using it in webformB, etc.
But the idea in general is to pass that value along, by query string or POST value or Session value or some other more stateful means, when redirecting from one form to the other.
I guess you have to resort to either passing the value from A to B in the query string or storing the value in Session and reading afterwards.
So would be a
Response.Redirect(string.Format("~/WebFormB.aspx?YourVariable={0}",HttpUtility.UrlEncode(ListBoxWebformA.SelectedValue));
and you can read it in Form B like
Request.QueryString["YourVariable"]
If the values are not sensitive this approach above would be the best.
If they are... To store in Session:
Session["YourVariable"] = ListBoxWebformA.SelectedValue
And to read...
if (Session["YourVariable"] != null) {
var listAValue = Session["YourVariable"].ToString()
}

How do I bring a string from one aspx.cs page to another?

I want to use a string that I have been using in one aspx.cs file over to another. I know this is easy, but how do I go about doing that?
You can do it in a query string. On your first page:
Response.Redirect("Second.aspx?book=codecomplete");
and on the second page
string book = Request["book"];
This method will allow your users to see what you are passing to a second page. Alternatively you can place it in session object. To place it use:
Session["book"] = "codecomplete";
and to get it back use:
string book = Session["book"] as string;
As a third alternative, you can use Server.Transfer. Use this method if you want to go to the second page on the server side. But notice that your user will continue to see the url of the first page on address bar.
On page 1:
this.SomeProperty = "codecomplete";
Server.Transfer("SecondPage.aspx");
On page 2:
string book = (PreviousPage as Page1).SomeProperty;
You can either send it using a querystring or you can define a session variable to store it.
The best option depends on what you want to use that string for.
Query string
Response.Redirect(page.aspx?val=whatever);
THEN in page.aspx
string myval = Request["whatever"]
OR
Server.Transfer("page.aspx", true);
Will perserve the form values from the first page if you want dont to make the switching of pages transparent
Another option is cross-page postback.
http://msdn.microsoft.com/en-us/library/ms178139.aspx
I strongly urge you to use the session only if absolutely neccessery , it takes valuable server resources.
Use the QueryString, it's really simple to use it, you just add a "?" after the aspx and write the value you want to pass for example:
page.aspx?val=this_is_a_value_passed_to_this_page.
When in page.aspx, you read querystring values like this:
string val = Request.QueryString["val"];
Response.Write(val);
This will generate the following response:
this_is_a_value_passed_to_this_page
A more complicated explanation can be found here:
https://web.archive.org/web/20210612112432/https://aspnet.4guysfromrolla.com/articles/020205-1.aspx
Use QueryString parameters or Session variables.
Keep in mind on the receiving page that when checking the Request or Session object, you should make sure that the value is not null before trying to use it to avoid unanticipated errors.
if (Session["VariableName"] != null) {
string varName = Session["VariableName"].ToString();
// use varName
}
Or
string varName = (Session["VariableName"] ?? "").ToString();
Likewise, if you are passing a numeric value, make sure that it is the correct data type before casting or converting and using it.
if (Session["IDValue"] != null) {
string idVlaueString= Session["IDValue"].ToString();
int idValue = 0;
bool isInt = int.TryParse(idValueString, out idValue);
if (isInt) {
// use idValue
}
}
If you only want the variable to last within that one call to another page, I advise using Context.
In the first page use:
Context.Items.Add("varName", varData);
And then on the called page use:
Context.Items("varName")
Read this article for more information: http://steveorr.net/articles/PassData.aspx
Check out an article on Alliance titled "Passing Data the .NET way" that shows how to accomplish this. The best part of this solution is that it doesn't use any query string variables that the user can see, nor does it require you to place it in the session state.
The short of it is:
On the first page (Default.aspx) create a hidden text box (txtMessage):
<asp:TextBox ID="txtMessage" runat="server" Visible="False" Text="" />
Then add a method in the code behind:
Public ReadOnly Property MessageForwarded() As String
Get
Return txtMessage.Text
End Get
End Property
Finally, you can dynamically set the value of the hidden textbox
txtMessage.text = "Hello there"
On the second page add a reference:
<%# Reference Page="Default.aspx" %>
and then load the data from the first page using the syntax:
Dim objSource As Source = CType(Context.Handler, Source)
If Not (objSource Is Nothing) Then
Response.Write(objSource.MessageForwarded)
End If
I've been using this for some time without any problems.
The query string is the good method, for passing a string value.
Check this solution and try it
response.redirect("link to your redirect page.aspx?userName="+string+"");
Here userName is the name given to the string which you want to get in another page.
And the string is the one which you are passing to next page.
Then get that string back by using
string str = Request.QueryString["userName"];
this is the esay way of getting the string value.

Categories