在我的代码中的什么时候这个 List<>变空?
namespace Messages
{
public partial class Email
{
List<Document> attachments = new List<Document>();
protected void Page_Load(object sender, EventArgs e)
{
foreach(Document document in documentList)
{
attachments.Add(document);
}
}
protected void btnSend_Click(object sender, EventArgs e)
{
sendMail(attachments);
}
}
}
正如您所猜到的,为了解释目的,我已经删除了这段代码,但这几乎就是我用它所做的一切。我有一种感觉,这与深/浅复制和克隆有关,如果是这样 - 有人可以帮助解释这里发生了什么以及我如何避免它/以不同的方式填充列表。
非常感谢,
丹
编辑:抱歉,我写的“documentList”实际上是这样的:
(List<Document>)Session[Request.QueryString["documentList"]]
所以你 - 它来自会话变量。使用断点,我可以看到附件列表填充得很好,但是当涉及到单击事件处理程序时,它是空的!?不为 null,只是 count == 0。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它变成空的,因为它没有存储在 ViewState 中(我从方法名称中假设这里是 asp.net webforms)。
请参阅如何:在视图状态中保存值 和 ASP.NET 页面生命周期概述
或者将值存储在会话中,请参阅如何:将值保存在会话状态
EDIT2:使用额外的信息 - 之前我遇到过此问题,已通过将代码从 Page_load 移出并移入辅助方法(更好)并在事件回调中使用它来解决。我最初确实声明事件回调发生在 Page_Load 之前 - 但是我刚刚检查过这一点,但事实并非如此,但是我确信我过去遇到过问题,在某些情况下,孩子控件,Page_Load 未完成 - 可能与验证有关。
无论如何,它可能应该按照以下几行重新编码 - 以消除 Page_load 和附件之间的依赖性。使用 IEnumerables(而不是列表)也可以很简洁 - 请参阅最后一个示例。
例如
,然后在回调中:
但是也值得建议使用 LINQ 来执行此操作,如下所示:
It becomes empty because it's not being stored in the ViewState (I'm assuming asp.net webforms here from the method names).
See How to: Save Values in View State and ASP.NET Page Life Cycle Overview
Alternatively store the value in the Session see How to: Save Values in Session State
EDIT2: with the extra info - I've had problems with this before that have been resolved by moving the code out of Page_load and into a helper method (better) and use this in the event callback. I did originally state that the event callback was coming before the Page_Load - however I've just checked this, and it doesn't, however I'm sure that I've had a problem in the past where in certain situations, with child controls, the Page_Load wasn't completing - possibly related to validation.
Anyway it should probably be recoded along the following lines - to remove the dependancy between Page_load and attachments. Using IENumerables (rather than lists) can also be neat - see the final example.
e.g.
and then in the callback:
however also worth suggesting using LINQ to do it like this: