Confirmation Box OnClientClick in ASP.NET

Smiley picture Smiley · Mar 30, 2012 · Viewed 8k times · Source

I'm trying to work on this website wherein I need to filter the data which are to be inserted into the database. For instance, I need to insert 'Hello World' to the database. However, it already exists. Therefore, I need to pop-up a confirmation box saying "The string Hello World already exists in the database. Are you sure you want to continue?"

My problem is that I don't know in which place in my code should I include my confirmation message. Please see below for referrence:

private bool CheckData(string myString)
{
    //Check database if myString already exists. 
    return;
}

private void btnSave_Click(Object sender, EventArgs e)
{
    CheckData(myString)
    //If the above is true, then the confirmation box should appear.
    //Do something to save myString to the database.
}

I'm programatically adding an OnClientClick Event handler to my button using the code below:

btnSave.OnClientClick = "confirmation('The string " + myString + " already exists in the database. Are you sure you want to continue?')";

My problem is basically what is the best way to handle this kind of scenario? Since I can't place this code on the btnSave_Click event (it will add the OnClientClick handler but it will only fire the next time the button was clicked).

Answer

derek picture derek · Mar 30, 2012

to do this via ajax, have the onClientClick call a js function that calls a .net handler to check if the file exists, and either:

  1. return true if no file exists so the postback occurs
  2. if the file already exists, popup a confirmation box and return the result of the confirmation box

otherwise, you can check if the file exists in the postback, but then you'll have to display a message and another confirm button to allow the user to overwrite the file. It will create two postbacks if the user decides to upload and overwrite an existing file.