[英]How to save values between different postbacks in view state in c# asp.net?
我陷入了一個問題,我正在創建一個100個問題的在線測試。 每個問題都有四個單選按鈕(選項),我想知道當我選擇選項時,當我按下“提交”按鈕時,如何使瀏覽器記住每個問題的選定值。 我想獲取提交按鈕上的值嗎? 我正在使用兩個屬性liek“ CurrentPageNo”和“ IncrementCount”來使用viewstate設置/獲取其值。 這是我的代碼:
public void NavigateRecords()
{
//CurrentPageNo = 1;
PagedDataSource pds = new PagedDataSource();
pds.DataSource = dt.DefaultView;
pds.AllowPaging = true;
pds.PageSize = 1;
// Set the PagedDataSource's current page
pds.CurrentPageIndex = CurrentPageNo;
lblCurrentPage.Text = "Page No: " + (CurrentPageNo + 1).ToString() +
" of "
+ pds.PageCount.ToString();
btnPrev.Enabled = !pds.IsFirstPage;
btnNext.Enabled = !pds.IsLastPage;
btnFirst.Enabled = !pds.IsFirstPage;
btnLast.Enabled = !pds.IsLastPage;
btnSubmit.Visible = pds.IsLastPage;
repeaterItems.DataSource = pds;
repeaterItems.DataBind();
SelectedValue = rblOptions.SelectedValue;
Dictionary<string, string> values = new Dictionary<string, string>();
for (int j = 3; j < 7; j++)
{
values.Add(dt.Rows[IncrementCount][j].ToString(), dt.Columns[j].ToString());
}
//var options = repeaterItemsFindControl("rblOptions") as RadioButtonList;
//options = new RadioButtonList();
rblOptions.DataSource = values;
rblOptions.DataTextField = "Key";
rblOptions.DataValueField = "Value";
rblOptions.DataBind();
lblMsg.Text = rblOptions.SelectedValue;
}
您需要創建一個會話來存儲您的答案。 因此,創建一個要在該會話中放置的List
或類。 然后在頁面加載中檢查會話是否存在。 如果確實將會話轉換為原始類型。
List<string> Questions;
protected void Page_Load(object sender, EventArgs e)
{
if (Session["questions"] != null)
{
Questions = Session["questions"] as List<string>;
}
else
{
Questions = new List<string>();
Session["questions"] = Questions;
}
}
現在,您可以通過單擊按鈕為該會話添加答案。
protected void Button1_Click(object sender, EventArgs e)
{
Questions.Add("Answer 1");
Label1.Text = "There are " + Questions.Count() + " answers";
}
如果持續按下Button1
您會看到答案的數量增加了。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.