Search code examples
javascriptasp.nethidden-field

Javascript to pass value from server to client doesnt work


I have a fileupload control and a button in a webform.When i click on the button after selecting fileupload,it should save the image and rename it with a GUID.

protected void btnUpload_Click(object sender, EventArgs e)
{
    string fileName = string.Empty;
    string filePath = string.Empty;
    string extension = string.Empty;
    try
    {
        //Check if Fileupload control has file in it
        if (FileUpload1.HasFile)
        {
            // Get selected image extension
            extension = Path.GetExtension(FileUpload1.FileName).ToLower();
            //Check image is of valid type or not
            if (extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".gif" || extension == ".bmp")
            {
                //Cretae unique name for the file
                fileName = Guid.NewGuid().ToString() + extension;
                //Create path for the image to store
                HiddenField1.Value = fileName;
                filePath = Path.Combine(Server.MapPath("~/Images"), fileName);
                //Save image in folder
                FileUpload1.SaveAs(filePath);
                //Show the panel and load the uploaded image in image control.
                //pnlCrop.Visible = true;
        }

The above code works just fine,saves the image and passes the GUID to the hiddenfield.Now i want to pass the value of hiddenfield to a client side variable and then display it as an alert.

  <script type="text/javascript">
    function showfilename() {       
        setTimeout(function () {
            var dpGUID = document.getElementById('<%= HiddenField1.ClientID %>').value;
            alert(dpGUID);
        },3000)
    }
</script>

Reason for using timeout? Because i want to read value of hiddenfield after it has been assigned the value on button click.

Note:I am using two functions on Buttonclick.One on client side and other on server side as follows :

 <asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="Button" OnClientClick="showfilename()" />

Is it possible? If yes,what could be causing a problem?


Solution

  • Try using a RegisterClientScriptBlock

    protected void btnUpload_Click(object sender, EventArgs e)
    {
        /*All your code here*/
        //instead of HiddenField1.Value = fileName; write the line below
        ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "callJsFunction", "alert('" + fileName + "');", true);
    }
    

    and now you can get rid of the OnClientClick="showfilename() and the HiddenField