Analysis of JavaScript insertion methods in ASP. NET

Source: Internet
Author: User
Tags sha1 encryption javascript eval

I. Significance of JavaScript insertion in ASP. NET:

. 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.

ASP. NET articles and 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. Example of JavaScript insertion in ASP. NET

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 ), the following code should be added to the Page_Load event:

 
 
  1. if not page.isPostBack() then  
  2.  
  3. btnSave.Attributes.Add(“onclick”,”Javascript:return confirm(‘Are you sure to save?’);”)  
  4.  
  5. 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, a row is triggered once ). First, add the following code in the Datagrid declaration:

 
 
  1. ﹤asp:datagrid id="grd1" runat="server" OnItemDataBound = "ItemDataBound" ﹥  
  2.  
  3. …Columns definition here  
  4.  
  5. ﹤/asp:datagrid﹥  

The ItemDataBound method is called when the OnItemDataBound event occurs. Add the definition of this method to the Code POST file:

 
 
  1. Sub ItemDataBound(ByVal sender As Object, ByVal e As DataGridItemEventArgs)  
  2.  
  3. If e.Item.ItemType ﹤﹥ ListItemType.Header And e.Item.ItemType ﹤﹥ ListItemType.Footer Then  
  4.  
  5. Dim oDeleteButton As LinkButton = e.Item.Cells(5).Controls(0)  
  6.  
  7. oDeleteButton.Attributes("onclick") = "javascript:return Confirm ('Are you sure you want to delete" & DataBinder.Eval(e.Item.DataItem, "m_sName") & "?')" 
  8.  
  9. End If  
  10.  
  11. 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 the first column of column 6th of the Datagrid, and the data source 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 not the same, and they are the same in the preceding example). Therefore, the ClientID attribute of the control must be used.

 
 
  1. Protected Sub ItemEdit(ByVal source As Object, ByVal e As System.Web.UI.WebControls.DataGridCommandEventArgs)  
  2.  
  3. Dim sDateCtrl as string  
  4.  
  5. sDateCtrl = grd1. Items (e.Item.ItemIndex) . Cells(2). FindControl("txtDate") . ClientID  
  6.  
  7. 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 and 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.

 
 
  1. Sub Item_Bound(ByVal sender As Object, ByVal e As DataGridItemEventArgs )  
  2.  
  3. Dim itemType As ListItemType  
  4.  
  5. itemType = CType(e.Item.ItemType, ListItemType)  
  6.  
  7. If (itemType ﹤﹥ ListItemType.Header) And _  
  8.  
  9. (itemType ﹤﹥ ListItemType.Footer) And _  
  10.  
  11. (itemType ﹤﹥ ListItemType.Separator) Then  
  12.  
  13. Dim oSelect As LinkButton = CType(e.Item.Cells(5).Controls(0), LinkButton)  
  14.  
  15. e.Item.Attributes("onclick") = Page. GetPostBackClientHyperlink (oSelect, "")  
  16.  
  17. 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, it is not very common for a user to save the data to the database whenever the Dropdownlist option is changed. But it is also required to remind the user whether to save the data. 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:

 
 
  1. Dim sCmd as string   
  2.  
  3. sCmd=Page.GetPostBackClientHyperlink(btnUpdate, "")  
  4.  
  5. If not page.isPostback then  
  6.  
  7. Dropdownlist1.Attributes.add("onchange","ConfirmUpdate(""" & sCmd & """)")  
  8.  
  9. End if 

The ConfirmUpdate function is as follows:

 
 
  1. ﹤Script language=”javascript”﹥  
  2.  
  3. function ConfirmUpdate(cmd){  
  4.  
  5. if confirm(“Are you sure to update?”)  
  6.  
  7. eval(cmd);  
  8.  
  9. }﹤/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. Summary of JavaScript insertion in ASP. NET

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.

The JavaScript Insertion Method in ASP. NET is introduced here. I hope you can understand it.

  1. Analysis of ASP. NET MD5 and SHA1 encryption methods
  2. ASP. NET learning-CSS implementation multi-interface two methods
  3. Basic Analysis of Cookie programming in ASP. NET
  4. Analysis of ASP. NET Programming habits
  5. Introduction to ASP. NET JavaScript page Integration

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.