Persist c# objects across postbacks - c#

I've got an asp.net page that has c# code-behind that does some stuff in the Page_Load() method (like query a database and make a few other calls to populate objects with data). I then display this data on the page. This all works fine. I set up a couple of postbacks so that when a value in a listbox is clicked, a panel control is filled with the rest of the corresponding object's data. I thought postbacks were the right way to do this, but this causes the (entire class?) to be re-called, which re-initializes my objects and destroys the data I want to keep.
Will some form of partial-postback solve this problem, or is there a better way to implement what I'm trying to do?
I don't want to re-populate the objects every time a postback is called, as that takes a database query, and I want to avoid re-querying every time something is clicked...
I've found many questions regarding persisting Javascript objects, but nothing that really seems to address this. I'm using .Net 4.0

Put the objects into the Session for the current user.

Put all your initialization stuff in an (!IsPostback) { } and use partial postbacks. That way the initialization code doesn't get called again during the postbacks.

Why don't you cache the object?
Caching API, Using the Cache Object:
http://msdn.microsoft.com/en-us/library/aa478965.aspx#aspnet-cachingtechniquesbestpract_topic4

Related

Loading several DropDowns on page load faster

I have several DropDown controls on a Web Form which are filled using AJAX call to a method in a class.
I call methods as below:
FillDistricts();
FillVillages();
FillTowns();
I thought these independent calls are creating too many round trips to the server and therefore I altered the class to fill all the DropDowns at once.
I pass the names of all the DropDowns as an array to a class which has a method to populate those DropDowns in a loop.
I want to know whether it will make some difference in page loads.
Use Page.Cache to store the results in, if that cache doesnt exists load the items, and save them into the cache, and may the same results be queried again, check to see if its already in the cache if so load it from the cache

ASP.Net Maintain a list of objects for a button click event

I am creating an asp.net page which loads data from a (SQL) visual studio database file (.mdf).
The data is loaded into a list of User objects (List) which contain the user data obtained from the database. This data is then displayed in a ASP.net table with a check box in column one. This allows the person viewing the webpage to in theory select users via the check boxes.
I have an ASP.net button also on the same page which when clicked will cause a post-back and go through the table row's and correctly identify which rows have and have not been checked. I am able to get the user data at this point as the Page_Load event is fired and the database contents are re-loaded for the second time.
Obviously this could become quite expensive obtaining the full list of users on each Page_Load so I have started investigating using the IsPostBack variable which allows me to identify whether it is a button click or standard page load.
The problem I have when using IsPostBack is the database contents loaded into the List on the initial Page_Load event would now be equal to null as the call into the database would never occur. This is understandable expected behavior and my question is what would be the best way to preserve the contents of the list so the button click can access the data loaded from the database on the initial Page_Load, without having to do another database query?
Thanks.
If its not user specific data that you are taking about store it in Cache.
Asp.net Caching
If its use specific data store it in session.
Session
I would suggest caching the result from the database and then doing your binding as usual. There are other options such as storing it in the ViewState but that can lead to much bigger page sizes depending on the data (personally I'm not a fan of ViewState, but it is an option).
At the end of the day, there is a certain amount of data you need to make the page work, you can't get away from having to store & retrieve that data somehow, so it comes down to deciding what is the most maintainable (and expected) way that doesn't have unacceptable tradeoffs. In my opinion that would be caching the database result, but it really depends on the application.
How about keeping a private variable inside your class?
private List<myObject> _data = null;
private void Page_Load(object sender, System.EventArgs e)
{
if(!Page.IsPostBack)
{
_data = loadDataFromDb();
}
}
private void Button_Click()
{
if(_data != null)
//Do something with the data
}
-Updated: I think you can avoid postbacks this way, so you only load your data once.

Generate data-bound FormView fields on-the-fly

I have an existing ASP.NET 3.5 application with a webform containing a FormView control used to perform CRUD operations on a domain object. A new requirement adds some dynamic content to the domain object that needs to be reflected in the FormView. This means that I need to generate those controls on-the-fly based on the bound object.
I am using an ObjectDataSource for the FormView that returns the domain object for binding. The domain object will now have a property that returns a collection of Section objects with each Section containing a list of Questions. In the middle of my form, I need to display each section with the list of questions and a textbox that allows the user to input the answer.
I am able to generate the UI a number of different ways but I have yet to find a way that includes data for the dynamic fields when the page is posted back. Because I won't know the 'schema' until the FormView is data-bound, I'm wondering if I'm too late in the pipeline for postback data to be handled properly.
What is the best way for me to generate these fields so the data is posted back correctly?
UPDATE
I'm still looking for the best way to accomplish this task but I've found a solution that at least works. In short, I am creating the dynamic content in the FormView's DataBound event handler because this is the first place in the pipeline that I can always get references to the FormView's controls. Then I follow Muhammed's suggestion and pull the values right out of the Request.Form collection and put them into the EventArgs objects in the FormView's ItemInserting and ItemUpdating handlers.
This isn't so straight forward as each control has to have a unique ID that I can then use to locate the value - which isn't so bad. However, I had to implement custom logic in the data source to then map these values into the data-bound object.
All-in-all, not too bad but certainly not something I'd want to duplicate in other solutions so I'm hoping there's still a better way.
When you want to get the value from the dynamic generated field, you should get it from the Request.Form collection and pass it into the ItemInserting event of FormView. e.g.
protected void frmAsset_ItemInserting(object sender, FormViewInsertEventArgs e)
{
e.Values["FieldName"] = Request.Form[ControlClientID];
}
Please note, your controls should be recreated on postback to get the value.

Form reloading in C#.net

I have a form i am fetching many records from database that are rendering dynamical on from. When i am clicking on Delete button this is deleting as well but I want to re-render my form so user will feel that records is deleted completely. when i am writing code this.refresh(); this is not fetching values from database and i am not seeing record is completely gone. It is windows C# form.
The methods Form.Refresh and Form.Invalidate have nothing to do with causing the application to retrieve new data from the database.
Form.Refresh - redraws the form synchronously (i.e. Form.OnPaintBackground and Form.OnPaint are called directly on the current thread).
Form.Invalidate - redraws the form asynchronously (i.e. WM_PAINT message is sent to the window, so Form.OnPaintBackground and Form.OnPaint will be called by the UI thread when it handles messages).
In order to update records, you need to make your control retrieve updated data.
If you specify more details on how the Form pulls that data, someone can help you figure out how to update it. For example, are you using data binding? Did you write your own code to retrieve the records?
Basically, without seeing your code, I would say you can take whatever it is you are doing in the constructor and put it in a separate method (let's call it RefreshData). Then, call RefreshData after you delete records from the database.
So, you're creating new controls that represent the data. In that case, there's no mechanism to automatically do the updating work for you, you'll have to code it. You generally have two options:
Keep a reference to the controls you created, and remove them from the Form before updating it.
Implementing something more efficient, like maintain a Dictionary that maps from the Data Rows to the controls that represent it, so that you can go over the updated data, and for each row in your dictionary that disappeared from the data, remove the controls.
You may also want to consider using some control that has a built-in Data Binding mechanism that would save you lots of work. For example, a GridView.
Could you be looking for Invalidate() ?
If you are filling the form in constructor you need to extract loading code to a method.
Then call it on DeleteButton.OnClick event after performing delete.

Return updated POCO object attached to GridView control using Reflection

I have a Custom GridView Control derived from ASP GridView Control. Now on all the Forms i have been using my CustomGridView Control.
I attach a List object to DataSource of this CustomGrid, and also store this List into ViewState so that i can manipulate this object when ever grid performs any postback.
Now every time i do insertion, updation and deletion i have to manually write code for Data Manipulation in my all Form. i.e. retrive data from ViewState and then update data or delete data or insert data into that object and store it again into ViewState.
I want a way to automatically write Code in my CustomGridView class object i.e. at one place to take care of this task. My CustomGridView Control should able to update, insert and delete for all my forms without Form writing any code at all.
In the end when its time to save the data into persistent storage i should get the final POCO object from CustomGridView Control.
This can be achieved using reflection but how?
Can you please tell me how can i achieve this task? Or what would be the best approach that i should follow?
Thanks,
Huzefa
I question whether it is best practice to store your underlying datasource within the view state. Have you considered putting this list in the session instead? It would be easier to access and you wouldn't burden your users with inflated page sizes due to overweight viewstate.
If you need to go with your stated approach, could you consider putting the code into a base form instead of trying to wedge it in the gridview? That way you only need to write the code once but it's more reasonable than trying to hack the gridview itself.

Categories

Resources