1

ユーザーが FileUpload コントロールを使用して画像をアップロードできるようにする UpdatePanel を Web アプリケーションに追加しようとしています。このリンクを参考にしています。しかし、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>&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