Manipulating data in ASP.net 2.0 22: Adding a client Acknowledgement for deleting data _ self-study process

Source: Internet
Author: User
Tags button type eval

Introduction

In the previous tutorials, we've seen how to use the application framework, the ObjectDataSource, and the data Web controls that provide incremental, modified, and censored functionality. In the interface we have implemented to delete data, there is a delete button that, when clicked, causes the data to return and invoke the ObjectDataSource Delete () method. The Delete () method then invokes the method in the corresponding business logic layer and then enters the data access layer until the DELETE statement of the final operation database is invoked.

Although this interface has been able to allow users to delete records through Gridview,detailsview, or FormView controls, it lacks some hint information when the user clicks on the Delete button. If the user originally wanted to click on the Edit button, but accidentally clicked the Delete button, the record that would have been updated will be deleted. To avoid this kind of thing happening, in this tutorial, we will add a window that will display a reminder to the client when clicking the Delete button.

The Confirm (string) method of JavaScript displays the text that is passed as string arguments in a modal window, and the window displays two buttons-ok (OK) and cancel (cancel). (see Figure 1) the Confirm (string) method returns a Boolean type value based on the click of a different button. (Returns True if Click OK, return False if clicked Cancel (cancel))

Figure 1:javascript's confirm (string) method displays a modal, client-side window

If a false value is returned from the client's event handler during the submission of a form, the form will cancel the submission. With this feature, we can call confirm in the client event handler onclick of this Delete button ("Are you sure you want to delete this product?"). "), so that it returns a Boolean value. If the user clicks Cancel, confirm (string) returns False, so the form's submission is canceled. In the absence of return, this has been clicked on the Delete button product has not been deleted. Conversely, if the user clicks OK in the confirmation window, the postback will continue and the product will be deleted. Refer to the Confirm () method using JavaScript to control the form submission for more information.

When adding these useful client scripts, there will be subtle differences between using templates and using a CommandField. Therefore, in this tutorial, we will examine both the FormView and the GridView examples.

  Note: As discussed in this tutorial, when using client-side validation techniques, we assume that the user's browser supports JavaScript and that JavaScript support is enabled. If any of these assumptions are not met, then clicking the Delete button will return immediately without displaying a confirmation window.

First step: Create a new FormView that supports deletion

First, under the EditInsertDelete directory, Create a confirmationondelete.aspx page, add a FormView control, and then bind a ObjectDataSource to the control, which will be derived from the Productsbll class GetProducts () method to obtain product information. It also binds its delete () method to the Deleteproduct (ProductID) method of the Productsbll class. Make sure that the Insert and update label Drop-down box is (None). Finally, check the Enable paging multiple selection box in the FormView Properties window.

With these steps, you create a ObjectDataSource that declares the following statement:

<asp:objectdatasource id= "ObjectDataSource1" runat= "Server"
  deletemethod= "Deleteproduct" oldvaluesparameterformatstring= "original_{0}"
  selectmethod= "getproducts" typename= "ProductsBLL" >
  <DeleteParameters>
    <asp:parameter name= "ProductID" type= "Int32"/>
  </DeleteParameters>
</asp:ObjectDataSource>

Because the optimistic concurrency is not used in our previous example, you can delete the OldValuesParameterFormatString attribute.

Because this FormView has been bound to a ObjectDataSource control that only supports deletion, in ItemTemplate we simply provide the delete button without the need for a new and updated button. In the FormView declaration tag, you can delete the EditItemTemplate and insertitemtemplate that we no longer need. Take a little time to customize the ItemTemplate to show only a set of product properties. I've customized it, using

<asp:formview id= "FormView1" allowpaging= "True" datakeynames= "ProductID" datasourceid= "ObjectDataSource1"
  runat= "Server" >
  <ItemTemplate>
     
 

Having made these changes, we already have a full-featured page that allows users to display each product and to delete a product by simply clicking on a button. Figure 2 shows a screenshot of the examples we have completed in the browser.

Figure 2:formview Control displays a product

Step Two: Call the Confirm (string) method in the client onclick event of the Delete button

After creating the FormView, the final step is to configure the Delete button so that the JavaScript confirm (string) method is invoked when the user clicks on it. You can add client script to the Button,linkbutton,imagebutton client onclick event by using the OnClientClick property, which is introduced in ASP.net 2.0. Because we want the confirm (string) method to have a return value, you can simply set the property value to: Returns confirm (' Are you sure you want to delete this product? ')。

After the modification, the declaration syntax for this delete button should read as follows: 3 gives a screenshot of this hint operation. Click the Delete button to activate the confirmation window display. If the user chooses to cancel, the postback will be canceled and the product will not be deleted. Instead, the user selects OK, the postback continues, the ObjectDataSource Delete () method is invoked, and the corresponding record in the final database is deleted.

<asp:linkbutton id= "DeleteButton" runat= "Server" causesvalidation= "False"
  commandname= "delete" text= "delete "
  onclientclick=" return confirm (' Are your certain you want to delete this product? '); " >
</asp:LinkButton>

Just need so much!

Note: Strings that pass into the confirm (string) JavaScript method are marked with single quotes (instead of double quotes). In JavaScript, a tag string can be either single or double quotes. We use single quotes here to make sure that the OnClientClick is not affected by the double quote mark of the property itself.

Figure 3: Display a confirmation window when clicking the Delete button

Step three: Set the OnClientClick property for the Delete button in a CommandField

When you use Button,linkbutton directly in a template, or ImageButton, you can set a confirmation window for its OnClientClick property directly and return the return value of confirm (string) JavaScript. However, CommandField are some of the delete buttons built into the GridView or DetailsView, and they do not have the OnClientClick property themselves to set the declaration. Instead, we have to refer to the Delete button in the code that handles the GridView or DetailsView, their appropriate databound events, and then set its OnClientClick property there.

Note: When we set the OnClientClick property of the Delete button in the appropriate DataBound event handler, we already have permission to access the currently bound data. This means that we can extend the confirmation information and include details of the specific records, such as, "Are you sure you want to delete this chai product?" These customizations can also be implemented in the syntax of the data binding for the template.

To practice setting the OnClientClick property of the Delete button in a CommandField, we add a GridView to the page. Configure this GridView to use the same ObjectDataSource control as FormView. Also, the BoundFields attribute that restricts the GridView includes only the product name, classification, and vendor. Finally, in the GridView Properties window, check the multiple selection box for the Enable deleting. This adds a column of CommandField to the Columncollection collection of the GridView, and its Showdeletebutton property is set to true.

After making these changes, your GridView declaration tag should look like the following:

<asp:gridview id= "GridView1" runat= "Server" autogeneratecolumns= "False"
  datakeynames= "ProductID" Datasourceid= "ObjectDataSource1" >
  <Columns>
    <asp:commandfield showdeletebutton= "True"/>
    <asp:boundfield datafield= "ProductName" headertext= "Product"
      sortexpression= "ProductName"/> <asp:boundfield datafield= "CategoryName" headertext= "Category" readonly=
    "True"
      sortexpression= "CategoryName"/>
    <asp:boundfield datafield= "SupplierName" Supplier "readonly=" True "
      sortexpression=" SupplierName "/>
  </Columns>
</asp:gridview >

This commandfield contains a delete LinkButton instance and can be accessed in the RowDataBound event handler of the GridView. Once referenced, we can set its OnClientClick property accordingly. Create a new processor for the RowDataBound event by using the following code:

 protected void GridView1_RowDataBound (object sender, GridViewRowEventArgs e) {if (e) . Row.rowtype = = Datacontrolrowtype.datarow) {//reference the Delete LinkButton LinkButton db = (LinkButton) e.ro W.cells[0].

    Controls[0]; Get information about the product bound to the row Northwind.productsrow Product = (Northwind.productsrow) ( System.Data.DataRowView) E.row.dataitem).

    Row; Db. OnClientClick = string. Format ("Return Confirm" (' Are your certain you want to delete the {0} product? '); ", product.
  Productname.replace ("'", @ "\")); }
}

This event handler is invoked when the data is bound in code and the Delete button is referenced. In general, the following patterns are used:
ButtonType is a type of button used by CommandField, either Button,linkbutton, or ImageButton. By default, CommandField uses LinkButton, but can also be customized with CommandField ButtonType properties. Commandfieldindex is the original index in the CommandField columns collection in the GridView, and Controlindex is the index in the CommandField collection of the Delete button. The value of the Controlindex is determined by the relative position of the button in the CommandField and the other buttons. For example, if there is only one delete button in the CommandField, its index is 0. However, if there is an edit button in front of the delete button, the index value is 2. Because there are two controls in front of the delete button, one is the edit button and the other is LiteralControl, which isolates the edit button and the Delete button.

ButtonType obj = (buttontype) E.row.cells[commandfieldindex]. Controls[controlindex];

In our example, CommandField uses LinkButton, at the leftmost, the Commandfieldindex value is 0. Because there are no other controls except the Delete button, the value of Controlindex is also 0.

After referencing the delete button in CommandField, we can then get some product information from the current data column of the GridView. Finally, we set the JavaScript value for the OnClientClick property for the Delete button, which contains the name of the product. Because we tagged the string arguments for the incoming confirm (string) in single quotes, we have to filter the single quotes that might appear in the product's name. Specifically, we can escape the single quotation mark contained in the product name, "/".

After you have made these changes, click the Delete button in the GridView to display a customized confirmation (see Figure 4). If the user clicks the cancellation in the pop-up confirmation window, the postback will be canceled, thus preventing the deletion from occurring.

  Note: We can also use this technique in the code for DetailsView CommandField. For DetailsView, however, you need to provide a processor for the DataBound event because it has no rowdatabound events.

Figure 4: Click on the GridView Delete button to display a customized confirmation message window

Using Templatefields

One disadvantage of using CommandField is that it must be accessed through the index to its buttons, which causes the object to be converted to the corresponding button type (Button,linkbutton or ImageButton). Using "Magic Numbers" and hard-coded types can cause errors that are found only at run time. For example, if you, or other developers, add a new button (such as an edit button) to Commandfields at some point in the future, or change the ButtonType attribute, the existing code will be compiled smoothly, but when the page is accessed it may throw an unexpected or unexpected error. , these are directly determined by the code you write and the changes you make.

One alternative is to use the templatefields instead of the GridView or DetailsView Commandfields. You can include ItemTemplate in TemplateField, and you can set LinkButton or Button,imagebutton below ItemTemplate as in CommandField. And the OnClientClick properties of these buttons can be declared, as seen in FormView, or we can use the following pattern to access the appropriate DataBound event handlers in the code.
ControlID is the property value of the button ID, although this method still requires a hard-coded type of conversion, but no longer requires the index, you can change the interface and no longer run errors.

ButtonType obj = (buttontype) e.row.findcontrol ("ControlID");

Summarize

The Confirm (Stirng) method of JavaScript is a frequently used technique in the form submission process. When executed, this method displays a modal, client-side window that contains two buttons, an OK (OK) one cancel (cancel). If the user clicks OK, the confirm (string) method returns True, otherwise it returns false. This functionality, and the return of false in the event handler submitted by the form, causes the browser to cancel the form submission and can be used to display a confirmation window when a record is deleted.

By setting the OnClientClick property of a button control, you can combine this confirm (string) method with the client-side onclick event handler for the button control. When using the Delete button in the template-or in a FormView template, or a TemplateField in the DetailsView or the GridView-as we saw in the tutorial, we can display a declaration to access it or access it in code.

I wish you a happy programming!

Author Introduction

Scott Mitchell, with six asp/asp. NET book, is the founder of 4GuysFromRolla.com, has been applying Microsoft Web technology since 1998. Scott is an independent technical consultant, trainer, writer, recently completed a new book to be published by Sams Press, proficient in asp.net 2.0 within 24 hours. His contact email is mitchell@4guysfromrolla.com, or he can contact him through his blog http://scottonwriting.net/.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.