添加更新面板后,页面仍会刷新
本文关键字:刷新 更新 添加 | 更新日期: 2023-09-27 18:30:34
我试图将UpdatePanel添加到我的Web应用程序中,该应用程序允许用户使用FileUpload控件上传图像。我使用此链接作为参考。但是 UpdatePanel 似乎不起作用,文件上传后它会继续刷新整个页面而不是图像部分。下面是我的代码。
Aspx:
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always">
<ContentTemplate>
<table width="75%" align="center">
<tr>
<td colspan="5" class="auto-style1">
<h2 align="center">My Profile</h2>
<br />
</td>
</tr>
<tr>
<td id ="memberprofileimage" align="center" class="auto-style2">
<asp:Image ID="Image1" runat="server" src="image/defaultProfile.jpg" Width="200" Height="200"/>
<br />
<br />
<asp:Button ID="btnupdatepic" runat="server" Text="Update profile picture " OnClick="btnupdatepic_Click" />
<br />
<asp:FileUpload ID="FileUpload1" runat="server" Visible="false"/>
<br />
<asp:RegularExpressionValidator ID="RegularExpressionValidator1"
ControlToValidate="FileUpload1" Runat="Server" Visible="false" ErrorMessage="Only jpg files are allowed"
ValidationExpression="^.+'.((jpg)|(JPG))$"/>
<br />
<asp:Button ID="btnUpload" runat="server" Text="Upload" CausesValidation="False" OnClick="btnUpload_Click" Visible="false"/>
<asp:Button ID="btnCancel" runat="server" Text="Cancel" CausesValidation="False" OnClick="btnCancel_Click" Visible="false"/>
<br />
<asp:Label ID="lblUpload" runat="server" Text=""></asp:Label>
</td>
<td id ="memberprofiledetail" align="left" width="50%">
<b> Full Name
<br />
</b>
<asp:TextBox ID="txtFullName" runat="server" ReadOnly="True" Width="270px"></asp:TextBox>
<br />
<br />
<b>Contact </b> <br />
<asp:TextBox ID="txtContact" runat="server" ReadOnly="True" Width="160px"></asp:TextBox>
<br />
<asp:RegularExpressionValidator ID="revContact" runat="server"
ControlToValidate="txtContact"
ValidationExpression="^[0-9]{8}$"
ErrorMessage="Please enter your Contact Number." ForeColor="Red">
</asp:RegularExpressionValidator>
<asp:RequiredFieldValidator ID="rfvContact" runat="server"
ErrorMessage="Please enter your Contact Number."
ControlToValidate="txtContact" ForeColor="Red">
</asp:RequiredFieldValidator>
<br />
<b>Address
<br />
</b>
<asp:TextBox ID="txtAddress" runat="server" ReadOnly="True" Width="300px" Height="40px"></asp:TextBox>
<br />
<asp:RequiredFieldValidator ID="rfvAddress" runat="server"
ErrorMessage="Please enter your Address."
ControlToValidate="txtAddress" ForeColor="Red">
</asp:RequiredFieldValidator>
<br />
<b>Email
<br />
</b>
<asp:TextBox ID="txtEmail" runat="server" ReadOnly="True" Width="270px"></asp:TextBox>
<br />
<asp:RegularExpressionValidator ID="revEmail" runat="server"
ControlToValidate="txtEmail"
ValidationExpression="'w+([-+.']'w+)*@'w+([-.]'w+)*'.'w+([-.]'w+)*"
ErrorMessage="Please enter a valid Email." ForeColor="Red">
</asp:RegularExpressionValidator>
<asp:RequiredFieldValidator ID="rfvEmail" runat="server"
ErrorMessage="Please enter your Email."
ControlToValidate="txtEmail" ForeColor="Red">
</asp:RequiredFieldValidator>
<br />
<asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
<br />
<asp:Button ID="BtnDisplay" runat="server" Text="Edit profile" CausesValidation="False" OnClick="BtnDisplay_Click" />
<br />
<br />
<asp:Button ID="btnUpdate" runat="server" Text="Update Profile" OnClick="btnUpdate_Click" Visible="False" />
<br />
<br />
<asp:Button ID="btnChangePassword" runat="server" Text="Change Password" OnClick="btnChangePassword_Click" CausesValidation="False" />
</td>
</tr>
</table>
</ContentTemplate>
<Triggers>
<asp:PostBackTrigger ControlID = "btnUpload" />
</Triggers>
</asp:UpdatePanel>
代码隐藏:
protected void Page_Load(object sender, EventArgs e)
{
Page.Form.Attributes.Add("enctype", "multipart/form-data");
if (Session["LoginAs"] != "Member")
{
Response.Redirect("Login.aspx");
}
else
{
String nric = (String)Session["nric"];
if (!IsPostBack)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
con.Open();
SqlCommand cm = new SqlCommand("Select * from MemberAccount where nric = '" + nric + "'", con);
SqlDataReader dr;
dr = cm.ExecuteReader();
if (dr.Read())
{
txtFullName.Text = dr["fullname"].ToString();
txtAddress.Text = dr["address"].ToString();
txtContact.Text = dr["contact"].ToString();
txtEmail.Text = dr["email"].ToString();
}
con.Close();
}
Image1.Attributes["src"] = "MemberProfilePicture.aspx?";
Image1.Attributes["height"] = "200";
Image1.Attributes["width"] = "200";
}
}
protected void btnUpload_Click(object sender, EventArgs e)
{
String nric = (String)Session["nric"];
string filePath = FileUpload1.PostedFile.FileName;
string filename = Path.GetFileName(filePath);
string ext = Path.GetExtension(filename);
string contenttype = String.Empty;
switch (ext)
{
case ".jpg":
contenttype = "image/jpg";
break;
case ".JPG":
contenttype = "image/jpg";
break;
}
if (contenttype != String.Empty)
{
System.Drawing.Image uploaded = System.Drawing.Image.FromStream(FileUpload1.PostedFile.InputStream);
System.Drawing.Image newImage = new Bitmap(1024, 768);
using (Graphics g = Graphics.FromImage(newImage))
{
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(uploaded, 0, 0, 1024, 768);
}
byte[] results;
using (MemoryStream ms = new MemoryStream())
{
ImageCodecInfo codec = ImageCodecInfo.GetImageEncoders().FirstOrDefault(c => c.FormatID == ImageFormat.Jpeg.Guid);
EncoderParameters jpegParms = new EncoderParameters(1);
jpegParms.Param[0] = new EncoderParameter(Encoder.Quality, 95L);
newImage.Save(ms, codec, jpegParms);
results = ms.ToArray();
}
//insert the file into database
string strQuery = "Update MemberAccount Set profilepicture = @Data Where nric = @Nric";
SqlCommand cmd = new SqlCommand(strQuery);
cmd.Parameters.Add("@Nric", SqlDbType.VarChar).Value = nric;
cmd.Parameters.AddWithValue("@Data", results);
InsertUpdateData(cmd);
lblUpload.ForeColor = System.Drawing.Color.Green;
lblUpload.Text = "Profile Picture Updated.";
Page_Load(null, EventArgs.Empty);
}
else if (contenttype == String.Empty)
{
lblUpload.ForeColor = System.Drawing.Color.Red;
lblUpload.Text = "Please select your image before uploading!";
}
else
{
lblUpload.ForeColor = System.Drawing.Color.Red;
lblUpload.Text = "File format not recognised." + " Upload jpg formats";
}
btnCancel.Visible = false;
FileUpload1.Visible = false;
btnUpload.Visible = false;
btnupdatepic.Visible = true;
}
private Boolean InsertUpdateData(SqlCommand cmd)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
cmd.CommandType = CommandType.Text;
cmd.Connection = con;
try
{
con.Open();
cmd.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
return false;
}
finally
{
con.Close();
con.Dispose();
}
}
FileUpload
控件不适用于异步回发,因此它无法在 AJAX UpdatePanel
中工作。 如果您在 UpdatePanel 中使用 FileUpload 控件,您仍然需要完整回发。 AsyncPostBackTrigger
不会为文件上传控件做这个技巧。
AsyncFileUpload
控件。我们可以将其放置在更新面板内或更新面板之外
<cc1:AsyncFileUpload ID="AsyncFileUpload1" ... />
在此处查看有关 AsyncFileUpload 控件的完整文章。
所以,简而言之,FileUpload
控件需要完全回发才能运行。但是,其余控件仍可以利用 UpdatePanel 提供的异步回发。
您只需要在任何情况下使用后退触发器才能使FileUpload
控件从"更新"面板工作。
<Triggers>
<asp:PostBackTrigger ControlID="myButton" />
</Triggers>
注意:没有这样的属性:EventName
用于后退触发器。
阅读这篇关于这个概念的漂亮文章,了解更多信息。
您应该尝试将 AsyncPostBackTrigger 或较旧的 PostBackTrigger 添加到 Triggers 标签内的 UpdatePanel 中,如下所示:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always">
<Triggers>
<asp:AsyncPostBackTrigger ControlID="btnUpload_Click" EventName="Click" />
<!-- OR
<asp:PostBackTrigger ControlID="btnUpload_Click" />
-->
</Triggers>
<ContentTemplate>
控件 ID 获取或设置触发 UpdatePanel 控件的异步回发的控件的名称。