I am building a Asp.net Application. I need to save a HashTable in a session.
At page load i am writing
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Session["AttemptCount"]=new Hashtable(); //Because of this line.
}
}
Here problem is, when a user refresh the page, session["AttemptCount"] also get refreshed.
I want to know where should I declare
Session["AttemptCount"]=new Hashtable();
So that my seesion do not get refeshed.
EDIT In Global.asax, this session will get started, as soon as user opens the website. I want to creat this session only if user go to a particular page. i.e Login.aspx
Do it in the Session_Start method in your Global.asax like so...
protected void Session_Start(object sender, EventArgs e)
{
Session["AttemptCount"]=new Hashtable();
}
Update:
Then simply just do a check to see if the session variable exists, if it doesn't only then create the variable. You could stick it in a property to make things cleaner like so...
public Hashtable AttemptCount
{
get
{
if (Session["AttemptCount"] == null)
Session["AttemptCount"]=new Hashtable();
return Session["AttemptCount"];
}
}
And then you could just call on the property AttemptCount wherever you need like so...
public void doEvent(object sender, EventArgs e)
{
AttemptCount.Add("Key1", "Value1");
}
You could make a property like this in your page:
protected Hashtable AttemptCount
{
get
{
if (Session["AttemptCount"] == null)
Session["AttemptCount"] = new Hashtable();
return Session["AttemptCount"] as Hashtable;
}
}
then you can use it without having to worry:
protected void Page_Load(object sender, EventArgs e)
{
this.AttemptCount.Add("key", "value");
}
test if it exists first
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if(Session["AttemptCount"] == null)
{
Session["AttemptCount"]=new Hashtable(); //Because of this line.
}
}
}
though the session_start is better, you only need to uses it on one page but you can create it for each session.
Hashtable hastable_name=new Hashtable()
Session["AttemptCount"]=hastable_name
Look at Global.asax and the Application_Started (I think) and there is one for session started too.
Related
I'm trying to make an application where the administrator can change some global values that it will affect the application for every user.
I tried to use static
Class
public static class Inventario
{
public static int FiltroEtiquetas;
public static int NumLocalizacoes;
public static void GetInventario()
{
}
}
Page
protected void Page_Load(object sender, EventArgs e)
{
txtFiltroEtiquetas.Text = Inventario.FiltroEtiquetas.ToString();
txtNumLocalizacoes.Text = Inventario.NumLocalizacoes.ToString();
}
protected void btnSaveInventaryChanges_Click(object sender, EventArgs e)
{
Inventario.FiltroEtiquetas = Convert.ToInt32(txtFiltroEtiquetas.Text);
Inventario.NumLocalizacoes = Convert.ToInt32(txtNumLocalizacoes.Text);
Page.ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "ShowToast('OK', 'topCenter','success', 'Alterações Guardadas com sucesso.', '2000')", true);
}
Whenever i open the modal the value is always 0, it won't save the changes
On page load you are resetting the both the textboxes with your global variables and on button click you are doing reverse so its kind of reset. That's why you are seeing 0 value.
You need to remove the code from page_load or you need to apply some condition over that.
You can implement something like this:
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
txtFiltroEtiquetas.Text = Inventario.FiltroEtiquetas.ToString();
txtNumLocalizacoes.Text = Inventario.NumLocalizacoes.ToString();
}
}
I think its really not a good idea to use the static variable in this scenario. I think you are better off using a application variable.
I'd like to bind a List<StockInList> to a GridView, show them to user, and get them back(perhaps user will edit them) to do something else. However, when I retrieved the bound item stockInLists, it's null. Reason I guess is that ASP create a new Code-Behind class Add_Inventories to handle request, so I lost the access to my bound item stockInLists.
Am I doing something wrong? What should I do to get them back correctly?
public partial class Add_Inventories : System.Web.UI.Page
{
private ShoppingDbContext shoppingDbContext = new ShoppingDbContext();
private List<StockInList> stockInLists;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var stockInListsFromSession =(List<StockInList>)Session["stock_in_list"];
if (stockInListsFromSession != null)
{
//save the stockInLists in private filed, so that I can get them back, however it's null when method `Add()` invoke.
stockInLists=new List<StockInList>(stockInListsFromSession);
GridView1.DataSource = stockInLists;
GridView1.DataBind();
}
else
{
//...
}
}
}
protected async void Add(object sender, EventArgs e)
{
foreach (var stockInList in stockInLists)
{
shoppingDbContext.StockInLists.Add(stockInList);
}
await shoppingDbContext.SaveChangesAsync();
Response.Redirect(Request.Url.AbsoluteUri);
}
}
The data in variables are lost when page is refreshed(Scope), to prevent it we should use Sessions, viewstate etc or make that variable as static(Not recommended).
In your case value stored in stockInLists will be lost if the page is refreshed,
store its data in viewstate ViewState["stockInLists"] = stockInLists;
store its data in Session Session("stockInLists") = stockInLists; (Recommended)
make it a static variable private List<StockInList> stockInLists; (Not Recommended)
I hope you understand it :)
I am new to ASP.NET and I am trying to set session variable. I have one form (SelectPlayer.aspx) where I am trying to set the session but when I try to see the result on second page it does not show me any value. Below is my code.
SelectPlayer.aspx
public partial class SelectPlayer : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Session["player1"] == null)
{
lblSelectPlayer.Text = "Select Player 1";
}
}
protected void btnSelect_Click(object sender, EventArgs e)
{
Session["player1"] = "PlayerSession";
Response.Redirect("Score.aspx");
}
}
Score.aspx
protected void Page_Load(object sender, EventArgs e)
{
if (Session["player1"] == null)
{
Response.Redirect("SelectPlayer.aspx");
}
}
Change Response.Redirect("Score.aspx"); to Response.Redirect("Score.aspx", true);
The second parameter of a redirect indicates that you want to end the response. I've found in the past that setting a Session directly before doing a redirect without this second parameter can cause issues.
In my application I'm using a usercontrol for two pages: AddInfo.aspx and EditInfo.aspx.
The thing is that I want different thing to happen when saving the info, depending on which page the user is at (ie. what he's actually doing).
So what i'm wondering is if there's any way to use an if statement to find out which page that right now is using the user control? In that case my problem could be solved.
protected void SaveButton_Click(object sender, EventArgs e) {
if (//The page using the usercontrol = Edit.aspx) {
// do this...
}
else {
// do that...
}
}
Thanks in advance
protected void SaveButton_Click(object sender, EventArgs e) {
if (this.Page is EditInfo) {
// do this...
}
else {
// do that...
}
}
Where EditInfo is your page's class.
You could also define a Behavior property on your user control and set it in your Xaml code according to what you want in which page. This would be a nice way to avoid the need to know where you are.
protected void SaveButton_Click(object sender, EventArgs e) {
if (Request.Url.AbsoluteUri.Contains("Edit.aspx")) {
// do this...
}
else {
// do that...
}
}
I have created a composite control with sample details as follows. Basically, the first time on page load the control sets a view state variable and the problem is that on post back (when the button is clicked), the ViewState variable is null. I have researched extensively and I am not able to find a solution. I checked all the Microsoft recommended articles and also from other developers. This approach seem to work for everyone and I can't figure out what I'm doing wrong. If anyone can help, I would really appreciate it.
PS: This code may not work as it is only for illustrative purposes. but this is exactly what i'm doing in my code.
Public class Test : CompositeControl
{
private Button btnTest = new Button();
public string TestViewState
{
get
{
string s = (string)ViewState["test"];
return (s == null) ? String.Empty : s;
}
set
{
ViewState["test"] = value;
}
}
private void set()
{
TestViewState = "test";
}
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
set();
}
protected override void RecreateChildControls()
{
EnsureChildControls();
}
protected override void CreateChildControls()
{
base.Controls.Clear();
btnTest.ID = "btnTest";
btnTest.Click += new EventHandler(btnSubmitTest_Click);
if (!ChildControlsCreated)
Controls.Add(btnTest);
base.CreateChildControls();
}
protected override void Render(HtmlTextWriter writer)
{
btnSumbit.Render(writer);
}
protected void btnSubmitTest_Click(object sender, EventArgs e)
{
string test = TestViewState; // Viewstate value is null here!!!!!!
}
}
Are you sure that Page_Load is getting called? As far as I can remember that "notation" works only on pages and User Controls (didn't check that). Try overriding:
protected override void OnLoad(EventArgs e)
{
...
}
Test it with a Debugger.
Ok, the enableviewstate was disabled at the web.config level by another team member. Glad I found it. Thanks Arthur for confirming it worked for you.