About the implementation of ASP.net invoke JavaScript

Source: Internet
Author: User
Tags date definition contains eval header requires client javascript eval
Asp.net|javascript

This article combines the examples to explain how to use the client's JavaScript script to improve the execution efficiency of the program and achieve more functionality in the ASP.net application.

First, ASP. NET and JavaScript

. NET is the next generation of Microsoft's strategic core, ASP. NET is a concrete implementation of the. NET strategy in Web development. It inherits the simplicity and ease of use of ASP, and overcomes the disadvantages of poor structure of ASP program, difficult to read and understand. In particular, the introduction of server-side controls and event-driven patterns makes Web application development closer to the development of previous desktop programs.

In a variety of articles and books that introduce asp.net, the focus is on server controls and the. Net Framework SDK, As this is the latest and most revolutionary improvement in asp.net, in contrast, client script JavaScript (and VBScript), which occupies an important place in the past in web development, rarely mentions that there seems to be a server-side program that no longer requires client script. However, the server-side program after all requires a browser and Web server interaction, for ASP.net, is a page submission, the need to send a large number of data, and a lot of work, such as input validation or delete confirmation, can be achieved with JavaScript. Therefore, it is still necessary to explore how to use JavaScript in asp.net.


Second, the application of JavaScript example

1. To add a JavaScript event for a server control on a page

The server control ultimately generates the normal HTML, such as <asp:textbox> generate input text. Each HTML control in the form has its own JavaScript event, such as a onchange event in the TextBox, a button with an OnClick event, a ListBox with onchange events, and so on. To add a client-side event for a server control, you need to use the Attributes property. The Attributes property is a property of all server controls that is used to add custom tags to the resulting HTML. If you have a Save button btnsave on the Web form, and you want to be prompted when the user points to this button to be sure you want to save it (for example, once you save it, and so on), you should add the following code to the Page_Load event:

If not Page.IsPostBack () then

BTNSAVE.ATTRIBUTES.ADD ("onclick", "Javascript:return confirm (' Are you sure to save? ');")

End If

Note that ' return ', which is not a province, otherwise, even if the user points to cancel, the data will still be saved.


2. Add a JavaScript event for each row in the DataGrid

Suppose that each row of the DataGrid has a Delete button that prompts the user to be sure to delete the record when the user points to it, in case the user points to the wrong line, or simply accidentally points to the delete button.

Whatever the name of the Delete button, it cannot be referenced directly as in the previous example, because each row has a button that is a child control in the DataGrid. In this case, the Onitemdatabound event for the DataGrid needs to be used. The Onitemdatabound event occurs after each row of data in the DataGrid is bound to a DataGrid (that is, one row fires once). First, add the following code in the DataGrid declaration:

<asp:datagrid id= "Grd1" runat= "server" Onitemdatabound = "ItemDataBound" >

... Columns definition Here

</asp:datagrid> here describes the call to the ItemDataBound method when the Onitemdatabound event occurs, adding the definition of this method in the code-behind file:


Sub ItemDataBound (ByVal sender as Object, ByVal e as DataGridItemEventArgs)

If e.item.itemtype <> listitemtype.header and E.item.itemtype <> listitemtype.footer Then

Dim Odeletebutton as LinkButton = E.item.cells (5). Controls (0)

Odeletebutton.attributes ("onclick") = "Javascript:return Confirm (' Are you sure your want to delete" & DataBinder.Eval ( e.Item.DataItem, "M_sname") & "?") "

End If

End Sub

Because the header row and footer row of the DataGrid also fire this event, it is first judged that the row that fired this event is not the header row and the footer row. This assumes that the Delete button is in the 6th column of the DataGrid (the first column is 0), and the DataSource of the DataGrid contains a column named "M_sname"


3. Referencing controls in the DataGrid in edit state

The built-in editing function of the DataGrid makes it an editing method when the field is less recorded. Instead of entering a separate page to edit the record, the user can move the current line into edit mode by simply editing the button. On the other hand, there are JavaScript programs that need to refer to the name of the control. For example, many programs provide a date control to ensure the validity of date formats when users are required to enter a date, and a new window pops up when the user points the control icon for the user to select a date. You need to provide the ID of the text box that displays the date to the new window so that when the user selects a date, the value can be backfill into the text box.

If it is a normal server text box control, its ID is the same as the ID of the generated HTML input box, but the two IDs are not the same (as in the previous example) in the editing state of the DataGrid, which requires the ClientID property of the control.

Protected Sub Itemedit (ByVal source as Object, ByVal e as System.Web.UI.WebControls.DataGridCommandEventArgs)

Dim Sdatectrl As String

Sdatectrl = Grd1. Items (E.item.itemindex). Cells (2). FindControl ("Txtdate"). ClientID

End Sub

This assumes that the Itemedit method is a Dategrid Onitemedit event handler and contains a server text box control named Txtdate in the third column of the DataGrid.


4. Referencing asp.net automatically generated JavaScript programs

The so-called "server-side controls" are for developers, and there are no server and client points in the generated HTML source, both standard html,dhtml and JavaScript. It responds to user input because the event handlers for each control eventually generate a script that resubmitted the page to give the Web server the opportunity to respond again and handle it. Normally we don't have to know what this script is or call this script directly, but in some cases, calling this script appropriately can simplify a lot of work. Take a look at the following two examples.

Point to any location in the DataGrid to select a row

The DataGrid provides a built-in selection button that selects the current line when the button is clicked (you can set the SelectedItemStyle property so that the current row has a different appearance). However, the user may be more accustomed to point to any location can select a line, if fully implement this function is quite cumbersome. A good idea is to add a selection button, but hide the column and invoke the JavaScript script generated by this button when you click on either line.

Sub Item_bound (ByVal sender as Object, ByVal e as DataGridItemEventArgs)

Dim ItemType as ListItemType

ItemType = CType (E.item.itemtype, ListItemType)

If (ItemType <> Listitemtype.header) and _

(ItemType <> Listitemtype.footer) And _

(ItemType <> Listitemtype.separator) Then

Dim Oselect as LinkButton = CType (E.item.cells (5). Controls (0), LinkButton)

E.item.attributes ("onclick") = Page. Getpostbackclienthyperlink (Oselect, "")


End Sub

This assumes that the selection button is in column 6th. E.item represents a row, and from the generated HTML it adds an onclick event to each <tr>. The Page.getpostbackclienthyperlink method returns the client script generated by the LinkButton control in the page, where the first parameter is the LinkButton control, and the second parameter is a parameter passed to the control, usually null. If it's not a LinkButton control, there's a similar function getpostbackclientevent that readers can refer to MSDN.

Server-generated scripts conflict with manually-added scripts

Server events for server controls typically correspond to the corresponding events of the client control, such as the DropDownList SelectedIndexChanged event corresponding to the HTML <Select> onchange event. If you want to manually add a onchange event, you will generate two onchange on the client, and the browser will ignore one. For example, the user wants to save to the database whenever the option in DropDownList is changed (although not very common, but it does need to be), but also wants to remind the user if they do want to save. Obviously, the saved code should be placed in the SelectedIndexChanged event, and the work of the reminder should be manually added to the onchange event. The result is that two onchange can only perform one. The correct way to do this is to add an invisible save button to invoke the program generated by this button in the manually incremented onchange event.

The Page_Load method is as follows:

Dim Scmd As String

Scmd=page.getpostbackclienthyperlink (Btnupdate, "")

If not Page.IsPostBack Then

Dropdownlist1.Attributes.add ("onchange", "Confirmupdate" ("" & Scmd & ""))

End If


The Confirmupdate function is as follows

<script language= "JavaScript" >

function Confirmupdate (cmd) {

If confirm ("Are you sure to update?")

eval (cmd);

}

</Script>

This uses the JavaScript eval function to invoke a command contained in a string. Note that the string containing the command cannot be enclosed in single quotes because the automatically generated script includes single quotes, so here are two double quotes that represent the double quotes of the string itself.

Third, concluding remarks

The above is a brief discussion of several situations where JavaScript is inserted in asp.net. Properly inserting a client's JavaScript script in a server program can improve the efficiency of the program and provide a more user-friendly user interface.



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.