How can i maintain objects between ASP.NET page post backs ?
I have an ASP.NET web page.when i click one asp.net button, I will call my function (Save ) which will create an object of my custom class (UserDetails class) and save the details to DB.so this is a post back.After the post back again the same page will be displayed to user.At that time,I want to take the User object which i have created in the first function (Save ) . What is the best way to do this ? I know i can store this in a Session and access it. But i want to know whethere there is any other better way ?
Another option would be to store the object in the Cache using a unique key (e.g. "user" + id) and only store it's id in the current session or in the ViewState. During a postback, you can then retrieve the object from the cache.
With this approach you have several advantages:
The approach you're looking for is some kind of databinding mechanism that binds the values of an object (you may load from the db if it already exists) to your asp.net webform.
Basically you'd have the following:
Page.IsPostback
and if so, you create a new object and fill it with the values the user entered.This would look like (I'm writing it out of my head without a compiler, so take care :) )
public partial class MyPage : Page
{
private Person myPersonObj;
protected void Page_Load(...)
{
if(!Page.IsPostback)
{
//this is not a postback, so you may load an object based on an ID (i.e. in QueryString or create a new one
myPersonObj = new Person();
}
else
{
//it is a postback, so unbind the values
myPersonObj = new Person();
Unbind(); //the myPersonObj will be filled, the values are managed by ASP.net in the ViewState
}
}
//caution, overriding Page.DataBind()
private override void DataBind()
{
textBoxFirstname.Text = myPersonObj.FirstName;
...
}
private void Unbind()
{
myPersonObj.FirstName = textBoxFirstname.Text;
}
protected void btnSubmit_OnClick(...)
{
if(Page.IsValid)
{
Save();
}
}
private void Save()
{
//ideal layering with Interfaces
IPersonBL personBL = MyBLFactory.Get<IPersonBL>();
personBL.SavePerson(myPersonObj); //call the BL for further validation and then persisting
}
}
What I wanted to add yesterday, but forgot since I had to hurry:
You can as well store your objects in the ViewState or Session as others described, but I have experienced that it should be done as rare as possible due to the following "disadvantages" (from my point of view):
The advantage of the "databinding" approach I described is that you don't have these problems, with the "disadvantage" of having a new fresh object each time. You therefore have to take care of handling your object state, i.e. manually keeping id's through roundtrips etc..
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With