ASP.NET pickup - server side control article (2)

zhaozj2021-02-11  171

Tips 2: Master the client attributes and events of the control often see similar questions online: How to make the ASP.NET server-side control response client event? ASP.NET Server-side controls can respond to server-side events to write web pages like writing a Windows program. Sometimes we do not need to make the client running control and server interaction. The overhead of doing this: not only occupying network bandwidth, but also the CPU resources of the server, will also generate a Postback caused by the client browser "Refresh" Interface effect. If you add a client event code to the server-side control directly in the HTML code of the web form, just like this: You will find that when you press this button, there is no predetermined message box to pop up, but directly execute the response button within the server-side code button to press the Button1_Click method of the event (assuming we have tied the button Set this event). If you look at the source code of the client page, the button's onclick event is not written at all, but it becomes "JavaScript: __ dopostback (...)". In fact, this is part of the .NET Framework conversion work. With this "JavaScript: __ dopostback (...), you can implement a series of actions such as buttons, server-side response events. (About this automatic plus script, I will explain in the future article.) I want the control to respond to the event on the client, I must find another law. Fortunately, .NET has provided us with a rich interface to implement these features. All server-side controls (Button, Label, TextBox ...) have an attribute attributes - this is a very important property, which is a collection of server-side controls in the client corresponding to HTML element properties and events. With it, we can customize the behavior and appearance of the server-side controls on the client. Or just then Button1, this time we add this in the Page_Load event (outside the ispostback judgment): Button1.attributes.Add ("onclick", "Window.alert ('button is pressed"); re- After generating a project, browse the page again. This time we can finally see the message box that "button is pressed" is normally popped up. Turning back to explain this code: attributes is Button1 is also the property owned by all server-side controls. Add (...) is a method to Attributes belonging. The role is to add code to the control in the client's HTML tag, the first parameter Is the name of the property, the second parameter is the value of the attribute. Here we add a piece of pop-up message box to the button's onclick event. On the client, view the page source code, you can see the button's OnClick event contains this code (.NET Framework automatically generated "__dopostback (...)" followed, we use add to tell .NET Framework: "Join our code first!").

转载请注明原文地址:https://www.9cbs.com/read-5617.html

New Post(0)