Click here to Skip to main content
15,886,799 members
Articles / Web Development / ASP.NET

Confirm Box for File Replace using Client Callback

Rate me:
Please Sign up or sign in to vote.
3.00/5 (1 vote)
25 May 2009CPOL1 min read 23.2K   14   5
Ask user to replace a file or not

Introduction

You are providing a facility for uploading files to your webserver. Client can upload any file. Client doesn't know whether the file he is uploading is already present on the webserver or not. So you need to check and ask to replace an existing file.

Once a file is chosen by the user, we need to check whether the file exists on the webserver or not.

A full postback for this will make the file lost from FileUpload control. As the page and its controls are re-created, the page code runs on the server, and a new version of the page is rendered to the browser.

A full postback will be done only to save the file.

Background

To avoid losing client state and not incur the processing overhead of a server roundtrip, you can code an ASP.NET Web page so that it can perform client callbacks. In a client callback, a client-script function sends a request to an ASP.NET Web page. The Web page runs a modified version of its normal life cycle. The page is initiated and its controls and other members are created, and then a specially marked method is invoked. The method performs the processing that you have coded and then returns a value to the browser that can be read by another client script function. Throughout this process, the page is live in the browser.

Using the Code

ASP.NET
<asp:FileUpload ID="FileUpload1" runat="server" />       
<input type="button" id="hBtn" value="Save" onclick="CheckFile()" />
        
<asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" />
<asp:HiddenField ID="hdnIsOverwrite" runat="server" />
C#
public partial class _Default : System.Web.UI.Page, 
			System.Web.UI.ICallbackEventHandler
{
    protected bool returnValue;
    protected void Page_Load(object sender, EventArgs e)
    {
        // hide server side button
        btnSave.Style.Add(HtmlTextWriterStyle.Display, "none");
        String cbReference =
            Page.ClientScript.GetCallbackEventReference(this,
            "arg", "ReceiveServerData", "context","processError",false);
        String callbackScript;
        callbackScript = "function CallServer(arg, context)" +
            "{ " + cbReference + ";}";
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
            "CallServer", callbackScript, true);
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        FileUpload1.PostedFile.SaveAs(Server.MapPath
		(Path.GetFileName(FileUpload1.PostedFile.FileName)));
    }
    public void RaiseCallbackEvent(String eventArgument)
    {
        //dummy processing
        System.Threading.Thread.Sleep(5000);   
        //set return value
        returnValue = File.Exists(Server.MapPath(Path.GetFileName(eventArgument)));
    }
    public String GetCallbackResult()
    {
        return returnValue.ToString().ToLower();
    }
}
JavaScript
 <script language="javascript" type="text/javascript">
function CheckFile()
{
    var fu= document.getElementById("FileUpload1");
    var btn = document.getElementById("hBtn");
    if(fu.value=='')
    {
        alert('Please select a file.');
        fu.focus();
    }
    else
    {
        //fire request to server
        CallServer(fu.value,"filename");
        btn.disabled=true;
    }
}

function ReceiveServerData(rValue)
{
    var fu= document.getElementById("FileUpload1");
    var btnServer = document.getElementById("btnSave");
    var btn = document.getElementById("hBtn");

    //disable the button for further clicking
    btn.disabled=false;

    if(rValue=='true') // file exists
    {
        if(confirm('Are you sure you want to replace the file ?'))
        {
            document.getElementById("hdnIsOverwrite").value="true";
            //save file , you can also use __doPostback()
            btnServer.click();
        }
    }
    else
    {
        document.getElementById("hdnIsOverwrite").value="false";
        //save file , you can also use __doPostback()
        btnServer.click();
    }
}
function processError(rValue)
{
    alert(rValue);
}
</script>

Points of Interest

  • A good use of ClientCallback

History

  • 25th May, 2009: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralFile Uploaded functionality With confirmation Pin
Amarpreet kamboj10-Dec-12 23:46
Amarpreet kamboj10-Dec-12 23:46 
GeneralAnother solution Pin
Florian DREVET3-Jun-09 11:01
Florian DREVET3-Jun-09 11:01 
QuestionWill it work if client and server are on different machine? Pin
Sohel_Rana25-May-09 21:02
Sohel_Rana25-May-09 21:02 
AnswerRe: Will it work if client and server are on different machine? Pin
rcravens2-Jun-09 7:47
rcravens2-Jun-09 7:47 
GeneralI prefer... Pin
Seishin#25-May-09 9:01
Seishin#25-May-09 9:01 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.