1

我试图将 UpdatePanel 添加到我的 Web 应用程序中,它允许用户使用 FileUpload 控件上传图像。我使用这个链接作为我的参考。但是 UpdatePanel 似乎不起作用,文件上传后它会不断刷新整个页面而不是图像部分。下面是我的代码。

ASP:

<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>

后面的代码:

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

2 回答 2

3

FileUpload控件不适用于异步回发,因此它不能在 AJAX 中工作UpdatePanel如果您在 UpdatePanel 中使用 FileUpload 控件,您仍然需要完整的回发AsyncPostBackTrigger不会对 FileUpload 控件起作用。

如果您想异步上传文件,请使用:AsyncFileUploadcontrol。我们可以将其放置在更新面板内或更新面板外

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

在此处查看有关 AsyncFileUpload 控件的完整文章。

因此,简而言之,FileUpload控制需要完整的回发才能发挥作用。但是,其余控件仍然可以利用 UpdatePanel 提供的异步回发。

您只需要在任何情况下使用PostBackTrigger来使FileUpload控件从更新面板工作。

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

注意:没有这样的属性:EventName对于 PostBackTrigger。

阅读这篇关于这个概念的漂亮文章了解更多信息。

于 2013-09-09T06:04:56.823 回答
0

您应该尝试将AsyncPostBackTrigger或较旧的 PostBackTrigger 添加到您的 UpdatePanel 内 Triggers 标记中,如下所示:

<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 获取或设置为 UpdatePanel 控件触发异步回发的控件的名称。

于 2013-09-09T01:56:52.823 回答