Session Value becomes null on Page refresh - c#

I am trying to save the value in a session and then on page refresh, I am trying to use that value. But every time, it goes inside the loop .
I am using HttpContext.Current.Session because my class is inheriting from HTMLTable.
if (HttpContext.Current.Session["Id"] == null)
{
HttpContext.Current.Session["Id"] = "2";
}
string a = HttpContext.Current.Session["Id"].ToString(); //I get 2, WORKS HERE

Related

Session won't store attribute on PostBack when CheckBoxList is triggered

My problem is that my List is not being retained during PostBack.
I am saving it into
Page.Session["mine"]
My design page consists of 2 controls( a Label and a CheckBoxList).
Because the number of items will change, I use a CheckBoxList instead of individual CheckBox controls and load each item dynamically in the page_load();
I am unsure of what it is called, either a member, attribute, or property. But I do have a variable that each method of the class are able to call on that holds the location of all selected items on the CheckBoxList.
Private List<int> locCheck = new List<int>();
When the OnSelectedIndexChanged() is triggered, the locCheck is renewed and stored in Session
locCheck = new List<int>();
int num = 0;
foreach(ListItem li in CheckBoxList.Items)
{
if(li.Selected)
locCheck.Add(num);
num++;
}
if(locCheck.Count == 0) //for testing purpose
locCheck.Add(1); //2nd item
Page.Session["mine"]=locCheck;
I want to keep the selected checks on PostBack, but it never happens. In Visual Studio I have no problem. But when I load to server, I am using mono, I get the following message:
Object reference not set to an instance of an object
I have this in page_load
if(Page.IsPostBack)
{
locCheck = new List<int>();
locCheck = (List<int>) Page.Session["mine"];
Label.Text = String.Format("Is PostBack {0}/{1}", locCheck.Count, CheckBoxList.Items.Count);
}
else
{
Label.Text = String.Format("Is Not PostBack 0/{0}", CheckBoxList.Items.Count);
}
I know the problem is with this line because locCheck.Count never changes in Label.Text
locCheck =(List<int>) Page.Session["mine"];
I know I have to attach
if(Page.Session["mine"] != null)
But I don't believe it is currently necessarry. Due to testing purposes, it should always have locCheck with at least one element.
i couldn't find an answer, so i started from scratch. instead of checklists i use panels of checkboxes that turn invisible when not needed.
I am still uncertain about Sessions but I have found something strange.
For example:
Session["mine"] = locCheck; //where lockCheck has 4 elements
there are times that locCheck is set to null sometime between page_load to a button click.
i have found that when this is so, debug back to a point where locCheck is not null and has correct element values. then perform following:
Session["mine"] = locCheck;
and later on, you perform the following code in click event
locCheck = new List<int>();
locCheck = (List<int>) Session["mine"];
//then make your update:
locCheck[3] = 7;
Session["mine"] = locCheck;
for some reason, if i don't do this both Session["mine"] and locCheck become null and data is lost.
try to use this
locCheck = (List<int>) Page.Session["mine"].ToString();
why to use page.session when you can use only session.

Allow postback using if statement?

Is it possible to only allow postback from a
button click when an if statement is true?
Whenever the postback occurs from the else part of the statement it resets the lblPrice to 100
lblPrice.Text ="100"
int biggerPrice =500;
if (txb1.Text != "0" )
{
lblPrice.Text = biggerPrice.ToString();
else{
lblErr.Text = "Woops!";
}
You can use #html.action in a razor view which can utilise if / else blocks. It will call an mvc controller to manipulate your strings.
Comparing your values in the view is tricky. You would need to either put values in viewdata every page refresh or a static state class
(Dont do this; code smell).

Retrieve Values from asp control in c# code behind

I have looked extensively to find an answer to this question but I only get extremely close. I have a web form that I use to add and edit records. When a record is selected in the gridview, a session variable is set and then used on page load to populate the text fields. If the session variable is not set, the form will be blank and the logic run as a new record. My problem is that I can add a new record successfully - I debugged and checked to make sure the asp controls passed the proper values to the code behind - but I cannot edit a record successfully. For some reason, the code behind file does not retrieve the proper values from the text boxes. Instead, it keeps the original populated values thus defeating the purpose of the edit. I imagine it is a binding issue but I am unsure and have searched upon end. Here is my code behind file:
protected void Page_Load(object sender, EventArgs e)
{
resultOutput.Visible = false;//Output results as to whether or not a record was added successfully is automatically hidden at page load
//Checking to see if session variable has been created
if (Session["editID"] != null)
{
//Create objects to get recipe data
dbCRUD db = new dbCRUD();
Recipe editRecipe = new Recipe();
//Grabbing session ID
var id = Convert.ToInt32(Session["editID"]);
//Call method to retrieve db data
editRecipe = db.SelectRecord(id);
//Populate results to text boxes
recordID.Text = editRecipe.Recipe_ID.ToString();
addName.Text = editRecipe.Name;
addTypeDDL.SelectedValue = editRecipe.Meal;
addDifficultyDDL.SelectedValue = editRecipe.Difficulty;
addCookTime.Text = editRecipe.Cook_Time.ToString();
addDirections.Text = editRecipe.Directions;
//Change Button Text
submitRecord.Text = "Edit Record";
//Change Title Text
addEditTitle.Text = "Edit Recipe";
}
}
protected void submitRecord_Click(object sender, EventArgs e)
{
Recipe recipe = new Recipe();
dbCRUD newRecord = new dbCRUD();
//Variables for execution results
var modified = "";
int returned = 0;
//Creating the recipe Object to pull the values from the form and
//send the recipe object as a parameter to the method containing insert stored procedure
//depending on Add or Edit
//recipe.Recipe_ID = int.Parse(recordID.Text);
recipe.Name = addName.Text.ToString();
recipe.Meal = addTypeDDL.SelectedValue.ToString();
recipe.Difficulty = addDifficultyDDL.SelectedValue.ToString();
recipe.Cook_Time = int.Parse(addCookTime.Text);
recipe.Directions = addDirections.Text.ToString();
//Checking to see if the page is loaded for edit or new addition
if (Session["editID"] != null)
{
recipe.Recipe_ID = Convert.ToInt32(Session["editID"]);
//If recordID exists, recipe will be passed to UpdateRecord method
returned = newRecord.UpdateRecord(recipe);
modified = "has been edited.";
Session.Remove("editID");
}
else
{
//If recordID does not exist, record will be passed to InsertRecord method (new recipe)
returned = newRecord.InsertRecord(recipe);
modified = "added";
}
//Method returns 0 if successful, 1 if sql error, 2 if other error
if (returned == 1)
{
resultOutput.Text = "There was an sql exception";
resultOutput.Visible = true;
}
else if (returned == 2)
{
resultOutput.Text = "There was a non sql exception";
resultOutput.Visible = true;
}
else
{
resultOutput.Text = "\"" + addName.Text + "\" recipe " + modified;
resultOutput.Visible = true;
}
}
Any object passed to my edit method is successful, however, as I mentioned, it does not grab the newly updated text box values.
Did you try checking PostBack property , Your code is loading the data everytime the page is posted back. So when you update the values in the form and hit update button. The Page_Load method is called first and it reloads all the data (replaces your updated values on the form) and then hit the update button event handler. So everytime your old values are being saved.
You may remove the code from page_load method and put it where you are setting the Session["EditId"] value. This will solve your problem.
I would suggest using a static dataset and bind it to the recordsource of the gridview control. Whenever you wanna edit a record update the dataset simultaneously and rebind it to the gridview control....hope that helps:)

Accessing a string variable from one method to another which is declared globally is giving null value

I am working on a web app;ication based on asp.net with c#,I have two methods specified below.
public partial class ClerkReception_CreateRecords : System.Web.UI.Page
{
string patid;
protected void ddryear_textchanged(object sender, EventArgs e)
{
string month = "";
if (ddrmonth.SelectedItem.Text == "Jan")
{
month = "01";
}
else if (ddrmonth.SelectedItem.Text == "Feb")
{
month = "02";
}
else if (ddrmonth.SelectedItem.Text == "Mar")
{
month = "03";
}
string year;
year = ddryear.SelectedItem.Text;
string locid = Session["Location"].ToString();
patid = locid + month + year;//Ex:AT112013
myConnection obj = new myConnection();
//string result = obj.fnDisplayManualRecords(year, month, locid);
string result = obj.fnDisplayManualRecords1(patid);
txtlast.Text = result.ToString();
if (ddrmonth.SelectedItem.Text != null || ddryear.SelectedItem.Text != null)
{
txtlast.Visible = true;
lbllast.Visible = true;
BtnProceed.Visible = true;
}
}
This is a method used when a item is selected from dropdownlist,where the patid returns the value.
I need to access the same value of patid inside a another method shown below,Hence I declared the patid as global variable so that I can access the value in any method.But its giving null.How to retieve the vale from one method to another method?
protected void BtnProceed_Click(object sender, EventArgs e)
{
string x = patid;//shows null
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("select top 1(SUBSTRING(patientid,9,4)) as MaxpatientID from Patient_Data where PatientID like '"+patid+"%' order by PatientID desc;", cn))
{
try
{
cn.Open();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
//int Patcount;
if (rdr.Read())
{
int Patcount = int.Parse(rdr["MaxpatientID"].ToString());
// if(Patcount == 0)
}
}
}
catch (Exception ex)
{
// handle errors here
}
}
}
}
}
The global variables are created / intialized between postback in asp.net and they do not retain the values between postback as http is stateless protocol, you need to use ViewState for that. You can read more about ViewState and Stateless protocol over here.
To set value in ViewState
ViewState["patid"] = locid + month + year;//Ex:AT112013;
To get value from ViewState
string patid = ViewState["patid"].ToString();
View State
View state's purpose in life is simple: it's there to persist state
across postbacks. (For an ASP.NET Web page, its state is the property
values of the controls that make up its control hierarchy.) This begs
the question, "What sort of state needs to be persisted?" To answer
that question, let's start by looking at what state doesn't need to be
persisted across postbacks. Recall that in the instantiation stage of
the page life cycle, the control hierarchy is created and those
properties that are specified in the declarative syntax are assigned.
Since these declarative properties are automatically reassigned on
each postback when the control hierarchy is constructed, there's no
need to store these property values in the view state. You can read
more about viewstate here.
Welcome to the world of post backs, each post back recreates the page (class) variables, so you need to save it before post back or it will be gone.
Use a cache object, such as Session to maintain values between post back and page navigation. Session gives you the power to store and retrieve objects across multiple pages in your application, including just one if you are continually posting back to it.
You can use Session, like this:
Storing value in Session:
Session["ValueToKeep"] = "My important information";
Retrieving value from Session:
// Make sure it is in session cache before we try to get it
if(Session["ValueToKeep"] != null)
{
string valueINeed = Session["ValueToKeep"].ToString();
}
Note: All items stored in Session are Objects thus the usage of .ToString() on the Session item. An item is boxed as an object when inserted into Session, but must be unboxed (cast) when retrieved.
You class level variables are re-created on postback. You will need to persist them somewhere that continues across requests.. such as ViewState, Session, etc.
The best way to interact with two methods / functions / event-function in side class is just declaring its accessible modifiers to public and you can call any object of that class after initialize some value to it.
public void ddryear_textchanged(object sender, EventArgs e) {....}
public void BtnProceed_Click(object sender, EventArgs e) {....}
create one variable inside class like string x; and initialize it in constrictor { x="some text "; } this is how code works...
There are many ways to get the value of global parameter,
one way is to define the parameter as static

Storing an List<int> in viewstate

I have an aspx page which has the following:
A repeater with a linkbutton in each
The link button has a commandargument of an integer value
A user control
The idea is that when the user clicks on the linkbutton the value of the commandarguement is stored in a List. No problem you may think, however I need the value to be stored in an List in the usercontrol, not in the ASPX page. The List needs to be persisted across postbacks, so it also needs to be stored in the viewstate.
So I created a public property in the user control like so:
public List<int> ImageString {
get {
if (this.ViewState["ImageString"] != null) {
return (List<int>)(this.ViewState["ImageString"]);
}
return new List<int>();
}
set { this.ViewState["ImageString"] = value; }
}
And then I was hoping that from my aspx page I could add a line of code to add a value to the list like so:
this.LightBoxControl.ImageString.Add(value);
The problem I'm getting is that the the value is actually never added to the list. The count is always zero.
I'm sure its just that I've set the property up wrong, but I'm not sure how to right it..
Any help would be greatly appreciated.
Thanks
Al
Your getter is wrong. This is the correct variant:
get {
if (this.ViewState["ImageString"] == null) {
this.ViewState["ImageString"] = new List<int>();
}
return (List<int>)(this.ViewState["ImageString"]);
}
Here you first check whether there is something you need in ViewState already, and if there is no, you add it there. Then you return the item from ViewState - it is guaranteed to be there.
Your solution was bad because it did not place new List<int>() into the ViewState

Categories