1

I have a page where you can upload a document. If you click on upload, there are a few validation steps that are taken before the actual upload code is triggered. One of the steps is that I check if the File already exists. And if it does, I want to execute a Javascript confirm() method to ask the user if he wants to replace the file. If he selects yes, I write "yes" into a (ultimately hidden) label; if he selects no, I write "no" in it. I did that because I wanted to check from the code behind what the user selected and if he selected "no" I wanted to be able to NOT execute the upload.

I'm aware of the RegisterStartupScript() Method and I have already tried that. The problem there is that it doesn't execute it immediately. It executes after leaving the method in the code behind and loaded the page again. By that time the document is already uploaded, even if the user selected "no".

Here I check if the document exists and want to execute the Javascript method to prompt the user

if (File.Exists(Server.MapPath(filePath)))
{
    ClientScript.RegisterStartupScript(this.GetType(), "returnValue", "MyJavascriptFunction();", true);
}

Here's the step where I check the user's answer from the hidden label and act accordingly if he selected to cancel (it gets executed right after the above if statement where I want to call the JS function

if (PopUpReturnValue.Text == "no")
{
    throw new Exception("you cancelled");
}

I expected the javascript code to run as soon as I called it, and then continue with the next if statement, but instead it finishes the entire method and then executes the Javascript Code. Is there a way to have it run how I expect it to?

Many thanks in advance!

wazz
  • 4,953
  • 5
  • 20
  • 34
MrAnon
  • 11
  • 1
  • have you used script manager / updatepanel? – Muhammad Aftab Sep 11 '19 at 08:58
  • Yes, I've used script manager. There is an update panel on the view but I don't exactly know what you mean with using it – MrAnon Sep 11 '19 at 11:35
  • Sounds like you might have to use Page Methods to combine front-end js with code behind. Or, you could use `OnClientClick` -- which calls a js function first, then goes to code behind -- to ask the user (every time) if you should delete existing files. Or, you could put a note on the page that says existing files will be overwritten...? Simple. – wazz Sep 11 '19 at 19:00

0 Answers0