简体   繁体   中英

Page still refresh after adding UpdatePanel

I trying to add UpdatePanel into my web application which allow user to upload image using a FileUpload control. I use this link as my reference. But the UpdatePanel don't seem to work, after file uploaded it keep refreshing the entire page instead of the image portion. Below is my code.

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>&nbsp;<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>

Code behind:

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();
        }
    }

The FileUpload control will not work with Asynchronous postback and therefore it will not work from within an AJAX UpdatePanel . In case you use the FileUpload control within an UpdatePanel, You will still need a full postback . AsyncPostBackTrigger will not do the trick for a FileUpload control.

In case you want to upload a file asynchronously , use: AsyncFileUpload control .We can place this within update panel or outside the update panel

<cc1:AsyncFileUpload ID="AsyncFileUpload1" ... />

Check the complete article here on AsyncFileUpload control.

So, In short , FileUpload control needs a full postback to function. However, the rest of the controls can still take advantage of the asynchronous postbacks provided by the UpdatePanel.

You need to use the PostBackTrigger only in any case to make the FileUpload control work from Update panel.

<Triggers>
        <asp:PostBackTrigger ControlID="myButton" /> 
 </Triggers>

NOTE: There is NO such property: EventName for PostBackTrigger.

Read this beautiful article on this concept for more.

You should try adding AsyncPostBackTrigger or the older PostBackTrigger to your UpdatePanel inside Triggers tag like this:

<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Always">
<Triggers>

 <asp:AsyncPostBackTrigger ControlID="btnUpload_Click" EventName="Click" />

<!-- OR 
 <asp:PostBackTrigger ControlID="btnUpload_Click" />
-->

</Triggers>
<ContentTemplate>

ControlID Gets or sets the name of the control that triggers an asynchronous postback for an UpdatePanel control.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM