讓我們分析一下source(見補充意見):
<script runat="server">
private Model.User _user;
protected void Page_Load(object sender, EventArgs e) {
// _user is stored in the session, the *very same* object
_user = HttpContext.Current.Session[Model.Common.UserSessionNameValue] as Model.User;
if (_user == null) {
_user = new Model.User();
}
var submit = Request.Form["Submit"] ?? String.Empty;
if (!String.IsNullOrWhiteSpace(submit)) {
var strUserId = Request.Form["UserId"] ?? String.Empty;
var userName = Request.Form["UserName"] ?? String.Empty;
var email = Request.Form["Email"] ?? String.Empty;
Int32 userId;
Int32.TryParse(strUserId, out userId);
// So, if you update _user's fields. What is stored in the session will be changed as well.
_user.UserId = userId;
_user.UserName = userName;
_user.Email = email;
// Regardless, if you "saved" back or not
if (submit.Equals("Submit with Save")) {
// because the left-hand side and the right-hand side are the same object
HttpContext.Current.Session[Model.Common.UserSessionNameValue] = _user;
}
Response.Redirect(Request.RawUrl);
}
}
</script>
這裏是你可以以避免無意中更新它做什麼:
<script runat="server">
private Model.User _user;
protected void Page_Load(object sender, EventArgs e) {
if (!string.IsNullOrWhiteSpace(Request.Form["Submit"])) {
var strUserId = Request.Form["UserId"] ?? string.Empty;
var userName = Request.Form["UserName"] ?? string.Empty;
var email = Request.Form["Email"] ?? string.Empty;
Int32 userId;
Int32.TryParse(strUserId, out userId);
_user = new Model.User()
{
UserId = userId;
UserName = userName;
Email = email;
}
if (Request.Form["Submit"] == "Submit with Save") {
HttpContext.Current.Session[Model.Common.UserSessionNameValue] = _user;
}
Response.Redirect(Request.RawUrl);
}
}
</script>
'更改對象page2'你怎麼樣改變對象?它是什麼類型的對象?我覺得你正在改變物體的屬性,這會產生你看到的結果。 – Jonesopolis
@Jonesopolis,你可以在我提供的項目中看到我的男人。這是一個User對象,然後我改變屬性的值。根據你所說的話,對象會自動保存回會話中?或者當我從會話中檢索對象時,我所做的只是獲取指向該對象的指針? – RoLYroLLs