我有一个page.aspx,用户可以在该页面中看到他们的信息,如姓名电子邮件和... 当页面加载时我从数据库中读取信息并将该obj保存在一个会话中:
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
using (MYEntities j = new MYEntities())
{
int idOfUser = ///from session i read id of user
try
{
InfoOfUser info = (from i in j.InfoOfUsers where i.UserID == idOfUser select i).Single();
Session["info"] =info ;
///set information to my page controls(txtbxs and ...)
}
catch (ArgumentNullException ex)
{
/// do ...
}
catch (InvalidOperationException ex)
{
/// do ...
}
}
}
}
我在点击事件中有一个编辑按钮:
protected void btnEdit_Click(object sender, EventArgs e)
{
using (MYEntities j = new MYEntities())
{
try
{
InfoOfUser info=Session["info"] as InfoOfUser;
info.Name=textboxName.Text;
///
///set inforamtion to info
///
j.SaveChanges();
}
catch (ArgumentNullException ex)
{
/// do ...
}
catch (InvalidOperationException ex)
{
/// do ...
}
}
}
问题是它不存储在我的数据库中。我的代码在哪里错了?当它存储信息时。我该如何删除该会话?保存后我无法删除该会话 因为我可以多次点击修改按钮。当用户转到另一个页面时,我该如何删除该会话?
答案 0 :(得分:2)
首先将实体附加到上下文然后保存
protected void btnEdit_Click(object sender, EventArgs e)
{
using (MYEntities j = new MYEntities())
{
try
{
InfoOfUser info=Session["info"] as InfoOfUser;
j.InfoOfUsers.Attach(info);
info2.Name=textboxName.Text;
///
///set inforamtion to info
///
j.SaveChanges();
Session.Remove("info");
}
catch (ArgumentNullException ex)
{
/// do ...
}
catch (InvalidOperationException ex)
{
/// do ...
}
}
}
这样可行。
<强>更新强>
要删除会话,请在成功修改后指定Session.Remove("info");
。