我的项目中有这个模块,其中有 2 个网格视图。一个用于主菜单模块,另一个用于其子菜单。我创建了一个列表,以便当选中主菜单模块上的行并且它具有相应的子菜单时,它将显示在子菜单网格视图中。
现在,当我回到该页面(我使用了会话(时,我可以看到我的 SubMenuGridview,但我注意到我勾选的复选框都消失了。
我的问题是我的页面如何记住我选中的复选框,无论是从我的主菜单模块网格视图还是从我的子菜单网格视图。
protected void cbxSelect_CheckedChanged(object sender, EventArgs e)
{
SubMenuGrid.DataSource = null;
SubMenuGrid.DataBind();
Business.SubMenuModules sub = new Business.SubMenuModules();
List<oSubList> oList = new List<oSubList>();
int counter = 0;
foreach (GridViewRow nRow in gvModuleList.Rows)
{
Int32 intModID = Convert.ToInt32(nRow.Cells[0].Text);
CheckBox chkBx = (CheckBox)nRow.FindControl("cbxSelect");
if (chkBx.Checked == true)
{
counter = counter + 1;
var oModList = sub.GetAllMenuPerModuleID(intModID);
if (oModList.Count > 0)
{
foreach (var rec in oModList)
{
oSubList olist = new oSubList
{
ID = rec.ID,
ModuleID = rec.ModuleID,
Submenu = rec.Submenu,
Description = rec.Description
};
oList.Add(olist);
}
Session["list"]=oList;
SubMenuGrid.DataSource = oList;
SubMenuGrid.DataBind();
}
}
}
}
这可以使用:
- 视图状态
- SessionPageStatePersister
- 基于自定义会话的解决方案
有关视图状态 - 请参阅评论中以下发布的链接。
基于自定义会话的解决方案
我们将使用预渲染方法。此方法在页面初始化之后但在保存其 ViewState 并呈现之前被调用。将 Request.Form 加载到会话变量中,并在每次调用非回发的页面时将其加载回去。
protected void Page_PreRender(object sender, EventArgs e)
{
if (!Page.IsPostBack && Session["PageState"] != null)
{
NameValueCollection formValues = (NameValueCollection)Session["PageState"];
String[] keysArray = formValues.AllKeys;
for (int i = 0; i < keysArray.Length; i++)
{
Control currentControl = Page.FindControl(keysArray[i]);
if (currentControl != null)
{
if (currentControl.GetType() == typeof(System.Web.UI.WebControls.TextBox)) ((TextBox)currentControl).Text = formValues[keysArray[i]];
else if (currentControl.GetType() == typeof(System.Web.UI.WebControls.CheckBox))
{
if (formValues[keysArray[i]].Equals("on")) ((CheckBox)currentControl).Checked = true;
}
else if (currentControl.GetType() == typeof(System.Web.UI.WebControls.DropDownList))
((DropDownList)currentControl).SelectedValue = formValues[keysArray[i]].Trim();
}
}
}
if(Page.IsPostBack) Session["PageState"] = Request.Form;
}
SessionPageStatePersister
抽象的 PageStatePersister 类表示封装页面状态存储和处理的基类。存储可以使用默认的 HiddenFieldPageStatePersister 类或 SessionPageStatePersister 来完成。使用 SessionPageStatePersister 时,.NET 服务器管理会话对象中的_VIEWSTATE,而不是窗体上的隐藏字段。更改状态存储如下所示:
protected override PageStatePersister PageStatePersister
{
get
{
return new SessionPageStatePersister(this);
}
}