在 ASP.NET 和 C# 中重复回发表单后的列表
本文关键字:表单 列表 NET ASP | 更新日期: 2023-09-27 18:36:33
我有一些代码使用 ASP.NET 和 C# 从文件夹中检索文件,我使用 CheckBoxList 显示它们,因为用户将能够选择其中一个文件,然后最后使用按钮,用户将能够通过电子邮件发送该所选项目。
我遇到的问题是,在选择项目并发送电子邮件后,页面重新加载并且项目重复,我不确定为什么或如何更正。任何帮助将不胜感激。
代码如下:
if (File.Exists(wavFile))
{
ListItemCollection itemCollection = CheckBoxList2.Items;
itemCollection.Add(new ListItem(wavFile));
itemCollection.Add(new ListItem("<asp:Panel ID='"Panel1'" runat='"server'"><object id='"MediaPlayer'" width='"100'" height='"42'" classid='"CLSID:22D6F312-B0F6-11D0-94AB-0080C74C7E95'" standby='"Loading Windows Media Player components...'"" +
"type='"application/x-oleobject'"><param name='"FileName'" value='"" + wavFile + "'"><param name='AUTOPLAY' value='0'>" +
"<embed type='"application/x-mplayer2'" src='"" + wavFile + "'" pluginspage='"http://www.microsoft.com/Windows/MediaPlayer/'" name='"MediaPlayer'" uimode='"none'" width='"300'" height='"42'">" +
"</embed></object></asp:Panel><br/><br/>"));
}
然后电子邮件由带有以下代码的按钮控制:
protected void btnSend_Click1(object sender, EventArgs e)
{
try
{
MailMessage mail = new MailMessage();
mail.To.Add("email@email.com");
mail.From = new MailAddress("email@email.com");
mail.Subject = claimNumber.Text;
mail.Body = "This is a test of the email again.";
System.Net.Mail.Attachment attachment;
attachment = new System.Net.Mail.Attachment(CheckBoxList2.SelectedValue);
mail.Attachments.Add(attachment);
mail.IsBodyHtml = true;
SmtpClient smtp = new SmtpClient();
smtp.Host = "smtp.email.com"; //Or Your SMTP Server Address
smtp.Credentials = new System.Net.NetworkCredential
("email@email.com", "pa$$w0rd");
smtp.EnableSsl = true;
smtp.Send(mail);
this.labelSuccessIndex.Text = "<br/><strong>The file has been emailed.</strong>";
}
catch (Exception ex)
{
labelError.Text = ex.Message;
}
}
将代码放在 if (!Page.IsPostBack)
中。这将在单击按钮后回发页面时阻止其执行。
if (!Page.IsPostBack)
{
if (File.Exists(wavFile))
{
// Your code here
}
}
假设此块中的代码
if (File.Exists(wavFile))
在第一次页面加载时运行,而不仅仅是将该块包装在另一个 if
if(!Page.IsPostback) { if (File.Exists(wavFile))... }
这将阻止代码再次添加到列表中。
如果未在初始加载时填充列表,则需要其他方法来避免第二次加载,或者清除列表并每次加载所有项目。