what is the lifespan of a datatable after an ajax call? - asp.net

I'm doing a jquery ajax call to my server side c#. The c# code fills a datatable then sends the data to the aspx page using a JavaScriptSerializer:
The datatable is initialized as a public:
public partial class _Default : System.Web.UI.Page
{
DataTable myDataTable = new DataTable();
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
//SqlDataReader builds loads data into dataTable...
HttpContext.Current.Response.Write(serializer(dataTable));
}
The aspx page finally creates a table from the data by posting it back to the aspx page.
My next task is to sort the rows ascending/descending when the table heading is clicked (using another ajax call).
I'd like to perform a sort operation similar to the accepted answer in this question:
Sorting rows in a data table
Will the datatable from the initial ajax call still be in memory?
Thank you.

No, the dataTable will not be in memoty anymore. Every time you create a request a new instance of _Default will be created. After the request has been handled, it will be destroyed.
If you want the DataTable to remain in memory, you should save it in the Cache or the Application object (HttpContext.Current.Cache / HttpContext.Current.Application).

Related

Sorting a gridview using a datatable, and datasource that is an ArrayList

http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.gridview.sorting.aspx
This article deals with creating a datatable first, then creating a gridview from it, to aid in sorting. My predicament is slightly different.
I have a Gridview, that on Page_Load, I set the datasource to an ArrayList, and bind.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
this.GridView1.DataSource = RequestManager.Instance.GetAllRequests();
this.GridView1.DataBind();
}
}
Now I would like to sort this GridView, so on the aspx page, I set AllowSorting="true", and OnSorting="GridView1_Sorting". So far, so good. I have the SortExpressions set in the BoundFields, and when I click on it, I know the _Sorting event is triggered.
Now, since this is a postback operation, I cannot simply cast the datasource of the gridview to a DataTable to sort. Saving to ViewState is an option, but I cannot figure out how to do it.
I would like to use the simple solution on this page, except for the DataTable not being available to me. Thanks for looking.
If you're able to target .NET v3.5, I recommend using Linq. In your _Sorting event handler, get the array list you did in the Page_Load and rebind it.
For example, if the type contained in the array list are MyType instances that have properties named Default and SomeField:
protected void Grid_Sorting(object sender, GridViewSortEventArgs e)
{
Func<MyType, object> keySelector;
if(e.SortExpresion == "SomeField")
{
keySelector = dataItem => dataItem.SomeField;
}
else
{
keySelector = dataItem => dataItem.Default;
}
ArrayList dataItems = RequestManager.Instance.GetAllRequests();
this.GridView1.DataSource = dataItems.OfType<MyType>().OrderBy(keySelector);
this.GridView1.DataBind();
}
That will get you started, then later inspect the sort expression to see if it ends with ASC or DESC and conditionally call .OrderByDescending(keySelector).
Finally, I don't recommend stashing the list in ViewState, as the ObjectStateFormatter is only optimized for a handful of types. http://msdn.microsoft.com/en-us/library/system.web.ui.objectstateformatter.aspx
Maybe consider ASP.NET cache instead.

Where to store the datasets? - Session or Cache in ASP.NET

freshly boarded the asp.net boat.
I have an asp.net page that initially displays some data in a gridview with pagination(with a dataset as its datasource). And, there are few textboxes to perform insertions or updations ( don't ask about the edit/insert options in the gridview itself!!).
I need few guidances regarding the right place to store datasets.
Im posting the simplified codebehind file, that uses viewstate to store the dataset, which I dont like.
enter code here
class xyx : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
GridBind();
}
}
protected void InsertUpdateButton_Click(object sender, EventArgs e)
{
1.perform insert or update data in the database
2.GridBind();
}
protected void GridView1_PageIndexChanged(object sender, EventArgs e)
{
GridView1.PageIndex = e.NewPageIndex;
GridView1.SelectedIndex = -1;
GridView1.DataSource = (DataSet)ViewState["DataSet"];
GridView1.DataBind();
}
private void GridBind()
{
DataSet ds = getDataFromDataBase();
GridwView1.DataSource = ds;
GridView1.DataBind();
ViewState["DataSet"] = ds;
}
}
Now apart from viewstate, what is the best choice to store the datasets??...
get the data from database everytime
Use a common Session variable Session["DataSet"] for all the datasets across all the pages(I have a few other pages with the same scenario )
Use Cache
I included session or cache because it is likely that the user might just be viewing the data rather than inserting or updating.
Also, In the Button click event instead of calling GridBind(), is it OK if I just updated the dataset in the viewstate rather than fetching data again from the database?
like -
DataSet ds = ViewSate["DataSet"] (or) Session["DataSet"] (or) Cache["DataSet"];
(perform updations or insertions upon the dataset)
Session(or)Cache(or)ViewState["DataSet"] = ds;
Generally:
If the data must be up to date, fetch it every time
If stale data is OK (or doesn't change often):
If the data is different per user, store in Session
If the data is the same for all users, use Cache or Application
If you wish to store large amounts of data per user do not use Session - you could run out of memory.
Depends upon many condition you should take care of these things first
Number of records in dataset.
Number of users.
If there are thousand of record then fetch only those record required. User some pager control.
here is an expample
For better use of paging.

Call add variable to GridView in UpdatePanel cause recreate page every time

I have that code in my page :
public partial class Utworz : System.Web.UI.Page
{
private List<Codes> Codes;
protected void Page_Load(object sender, EventArgs e)
{
this.GridView1.DataSource = Codes;
Codes = new List<Codes>();
}
protected void btn_AddKodManually_Click(object sender, EventArgs e)
{
Codes.Add(new Codes(code: this.TextBox1.Text, codeType: this.DropDownList1.SelectedValue));
this.GridView1.DataBind();
}
}
My page contains UpdatePanel in which I have form. I type data in this form and add to GridView.
and problem is that every time when I call Click method my Page was create new, and my variable Code also. Why this variable not save his state ?
Problem #1: The Codes variable is getting set to a new object every time the page loads. It will never have more than one code.
Problem #2: There is nothing here to hold the value of the Codes list from page view to page view. You need to store it somehow and retrieve it every time you want to rebind. For example, create a property called Codes and store the value in the viewstate. After adding a new code, rebind the grid.
I understand that you might expect the grid to hold it's state, but you're rebinding with a new object every time. Someone else might chime in here, but you may be able to restore the Codes object by calling:
Codes = this.GridView1.Datasource

Pass Key of Grid to Business Class via Object Data Source

In ASP.NET Webforms have an ASP.NET GridView connected to a C# class via an object data source
I have an ID set up as a DataKeyName in the grid. How do I pass this to the C# class when I update the grid?
Can pick up the grids data key name for the current row in the grids row updating event
protected void gvSearchResults_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//get handle on current grid row
DataKey keys = gvSearchResults.DataKeys[e.RowIndex];
customerId= GeneralUtils.GetIntegerKeyValue(keys, "customerID");
}
Then pass it to C# class using object data sources updating event
protected void odsHauliers_Updating(object sender, ObjectDataSourceMethodEventArgs e)
{
e.InputParameters["customerID"] = this.customerID;
}
Actually data key names are passed automatically by the datagrid to the object data source.

ASP.net DataTable doesn't store new rows

In my simple starter asp page I create a DataTable and populate it with two rows. The web site allows users to add new rows. My problem is the DataTable doesn't save the information. I've stepped through the code and the row gets added but the next time a row is added it's not there, only the original two and the newest one to get entered.
I have gotten around this, in an inelegant way, but am really curious why the new rows are being saved.
My code:
protected void Page_Load(object sender, EventArgs e)
{
_Default.NameList = new DataTable();
DataColumn col = new DataColumn("FirstName", typeof(string));
_Default.NameList.Columns.Add(col);
col = new DataColumn("LastName", typeof(string));
_Default.NameList.Columns.Add(col);
DataRow row = _Default.NameList.NewRow();
row["FirstName"] = "Jane";
row["LastName"] = "Smith";
_Default.NameList.Rows.Add(row);
row = _Default.NameList.NewRow();
row["FirstName"] = "John";
row["LastName"] = "Doe";
_Default.NameList.Rows.Add(row);
}
protected void AddButton_Click(object sender, EventArgs e)
{
DataRow row = _Default.NameList.NewRow();
row["FirstName"] = this.TextBox1.Text;
row["LastName"] = this.TextBox2.Text;
_Default.NameList.Rows.Add(row);
_Default.NameList.AcceptChanges(); // I've tried with and without this.
}
I've tried saving them to GridView control but that seems like quite a bit of work.
I'm new to ASP.Net but have done windows programming in C# for the last two years.
You're creating a new DataTable object each time the page loads.
You need to persist the DataTable object to session state or a static variable, or save the data to a database.
Remember that handling events like your button click requires a full postback. You don't run just the click code, you run your entire page lifecycle on a new instance of your page class. The new instance of your page class means a new instance of the datatable as well.
The issue here is that your DataTable is being created every time your page loads and it goes out of scope when your page has finished loading and been displayed to the user. To get your desired effect, you will need to store the DataTable in either Session, ViewState, cache, use a control like GridView that will automatically store the underlying data in its state, or something else.
Since you're new to ASP.NET, check out your options for state management.

Resources