2

I am currently doing an unpaid internship in C# and Asp.net. My employer has asked me to write out a javascript function so as to tell the user if they are sure if they want to delete a record from the database before deleting it.

After some research I was able to write out the Javascript function to tell the user if they are sure they want to delete this record before actually deleting it from the database.

The javascript function works. However now I have the problem of how do I call the backend C# function which will actually delete the record from the database from the front end javascript function which I have just written?

Here is my code:

Javascript function:

function watchdelete() 
{
    if (confirm("Are you Sure You want to delete this Manufacturer?") == true)
   {
        __doPostBack('btnDelete_Click','');//"PageMethods.btnDelete_Click();
   }
    else { }
}

Front end part which calls the javascript client side code attached to the delete button:

<asp:Button ID="btnDelete" runat="server" Text="Delete" OnClientClick=" return watchdelete()" OnClick="btnDelete_Click1" />

Back End C# function which I want to invoke in order to delete the record from the database: (Please note I will be happy as long as I call this function and it executes, you need not worry about its internal workings too much. Thank you)

protected void btnDelete_Click(object sender, EventArgs e)
{
    String com, command, findmodel;

    if (txtManufactureName.Text != "")                                      // If the manufacturer name is not null
    {
        if (txtManufactureName.Text == grdManufact.SelectedRow.Cells[1].Text) // And the manufacturer name must not be
        {                                                                     // Changed from selected one
            string strConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString2"].ToString();
            try
            {
                using (SqlConnection conn = new SqlConnection(strConnectionString))
                {
                    conn.Open();                                               // Connect to database
                    String moderated = (checkBoxModerated.Checked) ? "true" : "false";
                    findmodel = "SELECT * From VehicleModels WHERE ManufacturerID = '" + txtManID.Text + "';"; 
                    com = "SELECT * From VehicleManufacturer WHERE ManufacturerName = '" + txtManufactureName.Text + "' AND Ismoderated ='" + moderated + "';";
                    command = "DELETE From VehicleManufacturer WHERE ManufacturerName = '" + txtManufactureName.Text + "' AND Ismoderated ='" + moderated + "';";
                    SqlDataAdapter finder = new SqlDataAdapter(findmodel, conn);
                    DataTable dat = new DataTable();
                    int nummods = finder.Fill(dat);
                    if (nummods == 0)
                    {
                        SqlDataAdapter adpt = new SqlDataAdapter(com, conn);
                        DataTable dt = new DataTable();
                        int number = adpt.Fill(dt);                                // try to find record to delete
                        if (number == 0)                            // If there is no such record to delete
                        {                                           // Indicate this to user with error message
                            txtMessage.Text = "Sorry, there is no such record to delete";
                        }
                        else
                        {                                           // Otherwise delete the record
                            using (SqlCommand sequelCommand = new SqlCommand(command, conn))
                            {
                                sequelCommand.ExecuteNonQuery();
                                txtMessage.Text = "Manufacturer Deleted Successfully";
                                txtManufactureName.Text = "";       // Reset manufacturer name
                                txtDescription.Text = "";           // Reset Description
                                checkBoxModerated.Checked = false;  // clear moderated checkbox
                            }
                        }
                    }
                    else
                    {
                        txtMessage.Text = "Sorry. You must delete associated models first.";
                    }
                    conn.Close();                               // Close the database connection. Disconnect.
                }
                BindGrid();                                     // Bind Manufacturer Grid again to redisplay new status.
            }
            catch (SystemException ex)
            {
                txtMessage.Text = string.Format("An error occurred: {0}", ex.Message);
            }
        }
        else
        {
            txtMessage.Text = "Sorry. You cant change the manufacturer name before deleting";
        }
    }
    else
    {   // Otherwise give error message if manufacturer name missing
        txtMessage.Text = "Please enter a manufacturer name to delete";
    }
}

Any ideas will be appreciated.

1
  • Would you mind removing unrelated code from your sample and clarifying your problem to align with the accepted answer? (As side effect that painfully looking SQL injection will disappear from the sample). Also try to avoid thank you notes in the post. Commented Oct 3, 2014 at 3:29

2 Answers 2

3

Let's simplified your validation function to:

function confirmDelete(){
  return confirm("Are you Sure You want to delete this Manufacturer?");
}

Then your button with OnClientClick attribute will be something like

OnClientClick=" return confirmDelete()"  

As long as your validation function returns false .NET will not submit your code the server.

Sign up to request clarification or add additional context in comments.

6 Comments

Ok. So if I do it this way and it does return true what is the next step in order to call the backend function? Can you please explain how to call the backend function?
if it returns true it will execute the OnClick code that occurs on the code behind. What it seems it should be OnClick='btnDelete_Click'
Waaaaaallaaaaa. It works. You deserve an upgrade in your reputation Dalorzo. The keep it simple stupid principle works sometimes. Thanks a million man.
Wow. It works. Thanks a million Dalorzo. Haber un buena mannana.
Onclient click code gets executed first, namely the Javascript front end function. If it returns true, then the Onclick function gets automatically called, which is usually the backend codebehind function. There you have it in a nutshell as questions should be answered. What gets me is the amount of rubbish on the internet without people answering the question directly. Hope this helps a million more people.
|
0

To give people an understanding of how to call backend functions from client side Javascript I would like to put the answer here in my own words -> Simple plain English: Step 1. Write your Javascript function and place it on the client side and enable scripts whatever, not going into too much detail here. See the code snippet below for an example

   <script type = "text/javascript" >
    function watchdelete() 
    {
        return confirm("Are you Sure You want to delete this Manufacturer?");
    }
  1. Write your button or control front end code and ensure that your OnClientClick = the name of the javascript function you want to call plus the word return in front of it as in the example asp code shown in the original post.

  2. Ensure you fire up the backend C# function as per usual for example by double clicking on the button or control in design view of Visual Studio 2012 or 2013 or whatever so as to automatically build its backend function in the code behind page and code your backend function for what you want it to do obviously.

  3. When you have done step 3 correctly you should have OnClick= whatever your backend C# function was.

  4. Test your application. Once your front end javascript returns true it should automatically fire up your backend function as long as you have put a return statement as per the front end code shown in the original post or similar.

Life can be simple if only you want it to be. The choice is yours.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.