[英]How to hold a table of data for user edition (before saving in the the database)?
我一直在使用這種編程風格,在示例中已經看到它並開始使用它,因為它可以完成工作...我想知道其他程序員對此的看法...
因此,當您擁有GridView或基於RadView的控件(如RadGrid)時,您想在添加,編輯,重新排序和刪除行時跟蹤數據表。
使用會話保存數據表(或數據列表)可能不是最佳解決方案,因為用戶可能會打開兩個相同的網頁…使用ViewState保存數據可能是and選項...我一直在使用如下所示的方法:
public partial class DefaultPage : System.Web.UI.Page
{
protected DataLine DefaultDataLine()
{
DataLine dl = new DataLine();
dl = new DataLine();
dl.Number = 0;
dl.Title = "";
dl.Text = "";
return dl;
}
protected class DataLine
{
public int Number { get; set; }
public string Title { get; set; }
public string Text { get; set; }
}
protected static List<DataLine> tempLines;
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
tempLines = RadGridBindStartUpData();
}
}
protected void RadGrid1_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
{
RadGrid1.DataSource = tempLines;
}
protected void RadGrid1_InsertCommand(object source, Telerik.Web.UI.GridCommandEventArgs e)
{
GridEditableItem editedItem = e.Item as GridEditableItem;
List<DataLine> table = tempLines;
DataLine newRow = new DataLine ();
RadTextBox rtb;
rtb = (RadTextBox)editedItem.FindControl("RadTextBoxTitle");
newRow.Title = rtb.Text;
rtb = (RadTextBox)editedItem.FindControl("RadTextBoxDescription");
newRow.Description = rtb.Text;
RadNumericTextBox number = (RadNumericTextBox)editedItem.FindControl("RadNumericTextBoxNumber");
newRow.Number = number.Value.HasValue ? Convert.ToInt32(number.Value.Value) : 0;
table.Add(newRow);
}
// ...
因此,使用自定義對象(類)的靜態List變量(在Aspx頁面的代碼隱藏中聲明),並在編輯數據時對其進行更新。
您對這種方法有何看法? 可以嗎 如何保存表格格式的數據以供版本使用(在將其保存到數據庫之前)?
不完全確定要做什么,但是使用靜態變量可能不是您想要的。 靜態屬性在所有用戶/線程之間共享,因此所有並發用戶都將編輯相同的數據。
如果您只是想在回發后將少量數據集持久保存到同一頁面,請改用ViewState。 如果計划將大量數據填充到其中,請注意潛在的性能問題。
您提到了在會話中進行存儲,以及如果用戶打開頁面的多個副本等情況,這可能會導致問題...
我們有一個類似的問題,所以我在頁面后面的代碼中添加了一個屬性,並且在第一頁加載時(如果沒有回發等等),我生成了一個新的GUID。 然后,我將guid值用作會話密鑰,並且知道每頁它將是唯一的。
您可以像這樣創建一個spify屬性...
Public ReadOnly Property SessionDataKey() As String
Get
If ViewState("SessionDataKey") Is Nothing Then
ViewState("SessionDataKey") = Guid.NewGuid()
End If
Return ViewState("SessionDataKey").ToString()
End Get
End Property
簡而言之,我只是使用會話。
非常感謝您的答復! 在您的幫助下和一些研究中,我發現這兩種方法,在會話中存儲或使用靜態變量的確是錯誤的,至少出於我使用它們的目的……您的所有回答都是有幫助的,盡管我只能標記一如正確,我謹表示贊賞。
好吧,對於任何遇到相同問題的人,這是我在頁面中實現的內容:
public partial class ScriptAdd : System.Web.UI.Page
{
private List<MyItem> tempMyItems
{
get
{
//if (ViewState["tempMyItemsList"] == null)
// ViewState["tempMyItemsList"] = new List<MyItem>();
return (List<MyItem>)ViewState["tempMyItemsList"];
}
set
{
ViewState.Add("tempMyItemsList", value);
}
}
protected void Page_Load(object sender, EventArgs e)
{
// ...
}
}
然后在我想向臨時列表添加/插入/更新行時使用它:
List<MyItem> table = tempMyItems;
table.RemoveAt(idx);
MyItem newRow = new MyItem ();
// ...
table.Insert(idx, newRow);
最后,如果需要,我將所有項目存儲在數據庫中。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.