Solved

Problem with partial-page refresh with AJAX AsyncFileUpload in VB.NET

Posted on 2010-09-11
3
1,945 Views
Last Modified: 2012-05-10
I am trying to use AJAX AsyncFileUpload to upload image files to the server. When the image file is uploaded, I want it to immediately appear on the page.

My image to refresh is called "frenchlogo". When the upload event fires, it calls a subroutine AsyncFileUpload2_UploadedComplete which checks and saves the file, and updates the source of the image (frenchlogo.ImageUrl).

The Asyncfileupload and image are in the same Updatepanel.

What am I doing wrong ?

Thanks, Peter
Protected Sub AsyncFileUpload2_UploadedComplete(ByVal sender As Object, ByVal e As AjaxControlToolkit.AsyncFileUploadEventArgs)
If AsyncFileUpload2.HasFile then
    ' Determine new file name
    fileExtension = System.IO.Path.GetExtension(AsyncFileUpload2.Filename).ToLower()
    newfilename = "flogo-" & Session("sponsor") & fileExtension
    FolderToSave = Server.MapPath("\") & "Userdata\L-" & Trim(Session("Leaguenum")) & "\Advertisement\"

    ' Validate file is of correct type
    fileOK = False
    Dim allowedExtensions As String() = {".jpg", ".jpeg", ".png", ".gif"}
    For i As Integer = 0 To allowedExtensions.Length - 1
        If fileExtension = allowedExtensions(i) Then
            fileOK = True
        End If
    Next
        
    ' Save the file    
    If fileOK Then
        Try
            AsyncFileUpload2.PostedFile.SaveAs(trim(FolderToSave & newfilename))
            Outputmessage = "File uploaded!"
        Catch ex As Exception
            Outputmessage = "File could not be uploaded."
        End Try
    Else
        Outputmessage = "Cannot accept files of this type."
    End If

    ' Update database entry to indicate new banner name
        cmd.Connection = MyConn
        cmd.Connection.Open()     
        cmd.CommandText = "Update sponsors set sponsorlogofr = '" & newfilename & "' where sponsorid = " & Session("sponsor")
        cmd.ExecuteNonQuery()
        cmd.Connection.Close()

    ' Display the output message
    upload2Label.Text = Outputmessage

   End if

frenchlogo.ImageUrl = Foldertosave & newfilename
Showfrenchlogoimages.Visible = "true"

End Sub


<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <asp:Panel ID="Showfrenchlogoupload" runat="server">
            <tr>
                <td style="padding-left: 15px">
                    <ajaxToolkit:AsyncFileUpload runat="server" ID="AsyncFileUpload2" Width="400px"
	                    UploaderStyle="Modern" UploadingBackColor="#CCFFFF" ThrobberID="Throbber2"
	                    OnUploadedComplete="AsyncFileUpload2_UploadedComplete" />

                    <asp:Label runat="server" ID="Throbber2" Style="display: none;">
                        <img align="absmiddle" alt="" src="~/images/ajax-loader.gif" />
                    </asp:Label>
                    <br /><asp:Label id="upload2Label" runat="server" />
                </td>
            </tr>
        </asp:Panel>
        <asp:Panel ID="Showfrenchlogoimages" runat="server">
            <tr>
                <td align="center">
                    <asp:Image ID="frenchlogo" runat="server" />
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Button ID="Button4" Text="Change Logo" runat="server" OnCommand="ChangeAd"
                        CommandName="frenchlogo" />
                </td>
            </tr>
        </asp:Panel>
    </ContentTemplate>
</asp:UpdatePanel>

Open in new window

0
Comment
Question by:pbissegger
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
3 Comments
 
LVL 5

Accepted Solution

by:
pschrama earned 500 total points
ID: 33656454
I managed to get it working by using OnClientUploadComplete and adding a javascript function that refreshes the updatepanel. Also, the image url is stored in session because OnUploadedComplete seems to call the page seperately without including viewstate. Hope this helps.


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="AsyncUpload.aspx.cs" Inherits="Experimentation.Pages.AsyncUpload" %>

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
    function UpdatePanel1()
    {
        __doPostBack("UpdatePanel1", "");
    }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ToolkitScriptManager ID="ToolkitScriptManager1" runat="server">
    </asp:ToolkitScriptManager>
    <div>
        <asp:AsyncFileUpload ID="AsyncFileUpload1" runat="server" OnUploadedComplete="AsyncFileUpload1_UploadedComplete" OnClientUploadComplete="UpdatePanel1" />
        
        <asp:UpdatePanel ID="UpdatePanel1" runat="server">
            <ContentTemplate>
                <asp:Image ID="Image1" runat="server" />
            </ContentTemplate>
        </asp:UpdatePanel>
    </div>
    </form>
</body>
</html>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Experimentation.Pages
{
    public partial class AsyncUpload : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Image1.ImageUrl = this.UploadedImageUrl;
            if (string.IsNullOrEmpty(this.UploadedImageUrl))
                Image1.Visible = false;
            else
                Image1.Visible = true;
        }

        public string UploadedImageUrl
        {
            get { return Session["uploadedImageUrl"] as string; }
            set { Session["uploadedImageUrl"] = value; }
        }

        protected void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
        {
            if (AsyncFileUpload1.HasFile)
            {
                string extension = System.IO.Path.GetExtension(AsyncFileUpload1.FileName);
                string[] validExtensions = new string[] { ".jpg", ".gif", ".jpeg", ".png" };
                if (validExtensions.Contains(extension))
                {
                    string savefileName = Server.MapPath("~/Pages/Images/" + AsyncFileUpload1.FileName);
                    AsyncFileUpload1.SaveAs(savefileName);
                    this.UploadedImageUrl = "~/Pages/Images/" + AsyncFileUpload1.FileName;
                }
            }
        }
    }
}

Open in new window

0
 

Author Comment

by:pbissegger
ID: 33678198
Thank you so much for your help. I am very impressed with the effort you put into this.

It took me a couple of days to figure out how to translate to VB, but it seems to be working now.

Thanks, Peter
0
 

Author Closing Comment

by:pbissegger
ID: 33678204
Excellent solution !
0

Featured Post

Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
I've attached the XLSM Excel spreadsheet I used in the video and also text files containing the macros used below. https://filedb.experts-exchange.com/incoming/2017/03_w12/1151775/Permutations.txt https://filedb.experts-exchange.com/incoming/201…

739 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question