Clarification on Caching in ASP.NET - asp.net

We were working on data caching in ASP.Net where we have aspx page which has a Label and a Button.
Label will show Cached data if Cache is not null else it will load the data into cache and display "DataReloading" in the Label and a Click of a Button should clear the data from the cache and Label should show "DataReloading" and when we refresh the page again, label should show Cache Data
Expectation:
1) when First time page loads, Label should show "DataReloading" as Cache was empty and we are loading the data
2) when we Refresh , Label should show "Cache Data" as Cache was having "Cache Data" string in it
3) When we click button to Clear cache, Label should show "DataReloading" and when we refresh the page label should show Cache Data
The Problem that we are facing is on post button click we always get "DataReloading" in the Label.
Can anyone let us know where logic is wrong.
Here is a code from the aspx page
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace FormAuthenticationPractice
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadCache();
}
private string GetData()
{
return "Cache Data";
}
protected void btnClearCache_Click(object sender, EventArgs e)
{
Cache.Remove("Data");
lblData.Text = "DataReloading";
}
private void LoadCache()
{
if (Cache["Data"] != null)
{
lblData.Text = Convert.ToString(Cache["Data"]);
}
else
{
Cache["Data"] = GetData() as string;
lblData.Text = "DataReloading";
}
}
}
}

Related

How to maintain class after button click on page

I have a page in ASP .NET where when I access it, programmatically I set a value in the TextBox. When I click on the Button, I would like to update that value, but it gives me error:
Object not defined
Here is my code:
public partial class InsertValues : System.Web.UI.Page
{
DataProvider dataProvider = new DataProvider(); // This class contains all the querys I need to pull data
public MyValuesClass myValues; // This is my class where I get the data from my DB
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
startMyPage(); // Function that gets the values from the DataBase and sets my TextBox with the values.
}
else
{
}
}
private void startMyPage()
{
myValues = dataProvider.getValuesFromDB(); // Function that gets the values from a query and put them in my class, the values are. String "Banana" and Bool isNew = True
if (!myValues.isNew) //
{
txtFood.Text = myValues.food
}
else
{
myValues= new myValues();
myValues.isNew = true;
}
}
protected void btnSave_Click(object sender, EventArgs e)
{
if (myValues.isNew) // Object not defined.
{
dataProvider.addMyValues(myValues); // It Inserts into my DB
}
else
{
dataProvider.editMyValues(myValues); // It Updates into my DB
}
}
}
Basically, after I click on my "btnSave" the class myValues becomes null, and I get the error Object not defined, is there a way to maintain the class Values?
You need to refetch your myValues object on PostBack.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
startMyPage();
}
else
{
myValues = dataProvider.getValuesFromDB();
}
}
Only data that's stored in the ViewState or equivalent persistence mechanism will be kept between the initial page load and post backs, which is why values of your webforms page controls are persisted, but your code behind property isn't.
You can store things manually in the ViewState like this: ViewState["someKey"] = someObject;, but someObject has to be serializable. It looks like myValues is an ORM object, so it probably isn't serializable.
All Variables are re-initiated at every post back. you better store your class public MyValuesClass myValues in session or viewstate.

asp.net - object reference not set to an instance of an object for master page cs file

This is the code to my Master Page cs file. For some reason when I run my default page, I get an error that says "object reference not set to an instance of an object."
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Theming.MasterPages
{
public partial class Main : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string selectedTheme = Page.Theme;
HttpCookie preferredTheme = Request.Cookies.Get("PreferredTheme");
if (preferredTheme != null)
{
selectedTheme = preferredTheme.Value;
}
if (!string.IsNullOrEmpty(selectedTheme))
{
ListItem item = ThemeList.Items.FindByValue(selectedTheme);
if (item != null)
{
item.Selected = true;
}
}
}
switch (Page.Theme.ToLower())
{
case "darkgrey":
Menu1.Visible = false;
TreeView1.Visible = true;
break;
default:
Menu1.Visible = true;
TreeView1.Visible = false;
break;
}
}
protected void ThemeList_SelectedIndexChanged(object sender, EventArgs e)
{
HttpCookie preferredTheme = new HttpCookie("PreferredTheme");
preferredTheme.Expires = DateTime.Now.AddMonths(3);
preferredTheme.Value = ThemeList.SelectedValue;
Response.Cookies.Add(preferredTheme);
Response.Redirect(Request.Url.ToString());
}
}
}
The error appears to be at the switch statement but I can't figure out why. I've read on other posts that the value is assigning to the variable as null but I don't know why; I've got dark grey as an app theme. If anyone could please help me it would be very much appreciated.
I don't see Menu1 or TreeView1 defined anywhere in your markup. If those are in a content page, you can't access those in the MasterPage code-behind (there may be a way, but you can't directly access them the way you're trying to).

How to assign the value of user control property to aspx or codebehind in VB?

I have a user control with a public property which updates each time when a date from my calender(part of user control) is selected. Now I need to bring this value to page on which this user control is kept. How to do this.
I tried bringing the property value on page load event of aspx.vb(master page on which user control is present) but couldn't do it as page load is happening first and user property is loading next(null reference exception).
i tried this on page load of aspx hdnPPSeq.Value = PPCalender1.test1.ToString
Please share ideas to bring this value to aspx or codebehind in vb.
Create a method in usercontrol, which will return property value.
public partial class PassPropertyToPage : System.Web.UI.UserControl
{
string strSelectDateTime;
public string SelectedDateTime
{
set { strSelectDateTime = value; }
get { return strSelectDateTime; }
}
protected void Page_Load(object sender, EventArgs e){}
public string GetDateTime()
{
strSelectDateTime = <calendar value>;
return strSelectDateTime;
}
}
And in page, call the method to get the value:
public partial class AccessUserControlProperty : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Response.Write("DateTime selected in page: " + PassPropertyToPage1.GetDateTime() + "<br/>");
}
}

.net using and reaching public value

I wrote this code in .NET. When I want to change ‘s’ by clicking button2, it doesn’t change. I mean after clicking button2 and then I click Button1 to see the changes but nothing changes. How can I change and access the value of ‘s’ properly. What am I doing wrong?
public string s;
public void Button1_Click(object sender, EventArgs e)
{
Label1.Text = s;
}
public void Button2_Click(object sender, EventArgs e)
{
s = TextBox1.Text;
}
You need to understand how web applications work.
In each post back an instance of the class that handles the page is loaded, so when you click on button 1, the page does a post back and loads again, so this way the variable s isn't loaded with your content.
To make this code work, you need to save the S values on the page viewstate.
try replacing "public string s;" with this:
public string s
{
get { return (string)ViewState["myValue"]; }
set [ ViewState["myValue"] = value };
}
More Information about Page Life Cycle at: http://msdn.microsoft.com/en-us/library/ms178472(v=vs.100).aspx

Store and transfer values in a ascx control

I have a problem that I have been struggling with for some time, and it is regarding transfering values from one control to another.
Basically I have two .ascx controls. On control1: I have an email textbox called txtEmail. The txtEmail is used to save the email in the SQL table, and on update button click, I load Control2 that has a email textbox as well. I need the emailtext box from control1 to be available on email textbox on control2.
I have tried all kinds of different ways but to no avail. I even tried using delegates and events but I can't make it work.
Does anyone know how I can do this.
Regards
Please find below the code:
public event EventHandler Notify;
public string Email
{
get { return txtEmail.Text; }
set {Email= value ; }
}
//button that will handle the update
protected void btnUpdateDB_Click(object sender, EventArgs e)
{
var email = txtEmail.Text.ToString();
public BaseClass.BAL.MBAL m = new BaseClass.BAL.MBAL();
var s = new BaseClass.Controllers.m();
s.email=email;
if(m.save(s)!=0) txtMsave.Text="Saved....";
}
//second control
public void notifyEmailChange(object sender,EventArgs e)
{
txtUsername.Text = member1.Email;
}
protected void Page_Load(object sender, EventArgs e)
{
if(Page.IsPostBack)
{
member1.Notify += new EventHandler(notifyEmailChange);
}
}
public string email {
set { txtUsers.Text = value; }}
Maybe I am trivializing the problem, but if you are wanting to be able to read/write to the text box on each of the custom controls, just make a public property that reads and writes to the textbox on each of the two controls.
public string EmailAddress {
get {
return txtEmailAddress.Text;
}
set {
txtEmailAddress.Text = value;
}
}
Now the page that contains the two controls can read the email address from the first control and write it into the email address text box in the second control.
If I am misunderstanding the problem, let me know.
The way that I have done this in the past is to have
UserControl1 have a custom event called (for instance) Notify.
The containing control wires Notify to an EventHandler
When notify fires (on the update) the consuming event handler fires and this event handler updates the email on UserControl2
Might seem overengineered but because UserControl2 can't "see" UserControl1 I think this is the way to go
Example
In UserControl1
public event EventHandler Notify;
and within the update button click event handler
if(Notify != null)
{
Notify(this, new EventArgs());
}
In parent control
in Page_Load
ucUserControl2.Notify += new EventHandler(NotifyUserControl);
and to set the message
protected void NotifyUserControl(object sender, EventArgs args)
{
ucUserControl2.Email = ucUserControl1.Email;
}
You obviously need public properties in UserControls to expose the Email text

Resources