Apply Javascript in ASP. NET

Source: Internet
Author: User
Tags javascript eval
Summary

This article uses examples to describe the application in Asp.net.ProgramTo improve program execution efficiency and implement more functions.

I. ASP. NET and JavaScript

. NET is the core of Microsoft's next-generation strategy. ASP. NET is the specific implementation of. Net's strategy in Web development. It inherits the simplicity and ease-of-use of ASP and overcomes the disadvantages of poor structure and difficulty in reading and understanding ASP programs. In particular, the introduction of server-side controls and event-driven models makes web application development closer to desktop development in the past.

In a variety of Introduction to ASP. NETArticleAnd books focus on server controls and. net Framework SDK, because this is ASP. net is the latest and most revolutionary improvement. On the contrary, client-side scripting JavaScript (including VBScript), which occupies an important position in Web development in the past, is rarely mentioned, it seems that there is a server program and no client script is required. However, after all, the server-side program requires a browser interaction with the Web server. for ASP. net is a page submission, which requires a large amount of data to be transferred back and forth, and a lot of work, such as input verification or deletion confirmation, can be fully implemented using JavaScript. Therefore, it is still necessary to explore how to use JavaScript in ASP. NET.

Ii. JavaScript Application Example

1. Add JavaScript events to a server control on the page

The server control still generates common HTML, such as <asp: textbox> generating input text. Each HTML control in the form has its own JavaScript events, such as the textbox with an onchange event, the button with an onclick event, and The ListBox with an onchange event. To add client events to server controls, you must use the attributes attribute. The attributes attribute is an attribute of all server controls. It is used to add custom tags to the final HTML. Assume that there is a Save button btnsave on the web form, and you want to prompt the user whether to save the button (for example, once saved, it cannot be restored) When you click this button ), add the following in the page_load event:Code:

If not page. ispostback () then

Btnsave. Attributes. Add ("onclick", "javascript: Return confirm ('Are you sure to save? ');")

End if

Note that 'return' is not economical. Otherwise, even if the user clicks cancel, the data will still be saved.

2. Add JavaScript events for each row in the DataGrid

Assume that each row of the DataGrid has a delete button. When you click this button, you will be prompted whether you want to delete the record, in case that you have clicked the wrong row or accidentally clicked the delete button.

No matter what the delete button is, it cannot be referenced directly as in the previous example, because each row has such a button, which is a child control in the DataGrid. In this case, the onitemdatabound event of the DataGrid must be used. The onitemdatabound event occurs when each row of data in the DataGrid is bound to the DataGrid (that is, one row is triggered ). First, add the following code in the DataGrid declaration:

<Asp: DataGrid id = "grd1" runat = "server" onitemdatabound = "itemdatabound">

... Columns definition here

</ASP: DataGrid> the itemdatabound method is called when the onitemdatabound event occurs. Add the definition of this method to the Code POST 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 you want to delete" & databinder. eval (E. item. dataitem, "m_sname ")&"? ')"

End if

End sub

Because the row of the title and footer of the DataGrid will also trigger this event, you must first determine that the row that inspires this event is not the row of the title and footer. Assume that the delete button is located in column 6th of the DataGrid (the first column is 0), and The datasource of the DataGrid contains a column named "m_sname ".

3. reference the control in the DataGrid in the editing status

The built-in editing function of the DataGrid allows you to edit a record when there are few fields. Instead of entering a separate page to edit records, you can click the edit button to edit the current row. On the other hand, some javascript programs need to reference the control name. For example, many programs provide a date control when users need to enter a date to ensure the validity of the date format. When the user clicks the control icon, a new window is displayed for users to select a date. In this case, you need to provide the ID of the text box that shows the date to the new window, so that the value can be refilled into the text box after the user selects the date.

If it is a common server text box control, its ID is the same as the generated HTML input box ID; but in the DataGrid editing status, the two IDs are different (in the same way as the preceding example). Therefore, the clientid attribute of the control is used.

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

Here we assume that the itemedit method is the onitemedit event handler of dategrid, and the third column of the DataGrid contains a server text box control named txtdate.

4. reference the Javascript program automatically generated by ASP. NET

The so-called "server-side controls" are for developers. In the generated HTML source code, there is no distinction between the server and the client. They are both standard HTML, DHTML, and JavaScript. It responds to user input because the event handler of each control finally generates a script, which resubmit the page so that the Web server has the opportunity to respond and process it again. In general, we do not have to know what this script is or call it directly, but in some cases, calling this script appropriately can simplify a lot of work. See the following two examples.

● Click any position in the DataGrid to select a row

The DataGrid provides a built-in selection button. When you click this button, you can select the current row (you can set the selecteditemstyle attribute to make the current row look different ). However, users may be more accustomed to selecting a row at any position. It is quite cumbersome to implement this function on their own. A good idea is to add a selection button, but hide this column. The Javascript script generated by this button is called when any row is clicked.

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

Assume that the selection button is in column 6th. E. Item represents a row. In the generated HTML, an onclick event is added to each <tr>. The page. getpostbackclienthyperlink method returns the client script generated by the linkbutton control on the page. The first parameter is the linkbutton control, and the second parameter is the parameter passed to the control, which is usually null. If it is not a linkbutton control, there is a function similar to getpostbackclientevent. Readers can refer to msdn.

● The Script generated by the server conflicts with the script manually added

Server events of server controls generally correspond to events of client controls. For example, the selectedindexchanged event of dropdownlist corresponds to the onchange event of HTML <SELECT>. If you want to manually add an onchange event, two onchanges will be generated on the client, and the browser will ignore one. For example, the user wants to save the dropdownlist option to the database whenever it is changed (although not very common, but it does), but also wants to remind the user whether to save it. Obviously, the stored code should be placed in the selectedindexchanged event, and the reminder should be manually added with an onchange event. The result is that only one onchange can be executed. The correct method should be to add an invisible Save button and call the program generated by this button in the manually added 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>

The Javascript eval function is used to call the commands contained in a string. Note that strings containing commands cannot be enclosed by single quotation marks. Because the automatically generated script contains single quotation marks, two double quotation marks are used to represent the double quotation marks of the string.

Iii. Conclusion

The above briefly discusses several cases of JavaScript insertion in ASP. NET. Reasonably inserting the client's Javascript script in the server program can improve the program running efficiency and provide a more 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.