Add attributes and events for web user controls in ASP.NET

zhaozj2021-02-16  39

Add attributes and events for web user controls in ASP.NET

Author: Zheng Zuo 2004-04-02 in the early 1990s, Microsoft for Web programmers of Active Server Pages (ASP) revolutionized Web programming. It can utilize the very easy-to-use model to dynamically generate HTML on the web server, and it is easy to implement access to the database, as at that time, this is an attractive technology, including many web sites on the INTERNET It is written in ASP. My colleagues played more than ASP masters. I have experienced so many years without falling, I can see him. However, the technology is constantly developing, and the reference to a NET expert - Today, the state of Web programming is still behind. Therefore, Microsoft proposed a second-generation programming model --Web form. The web form model is part of the ASP.NET, while ASP.NET is part of the .NET framework. His programming model is based on an event. It is more like a Windows form programming. This is also an important reason I decided to learn to use him. I also watched some books in this area. The purpose of the article is to share experiences with ASP.NET beginners and peers that have not added custom events have been added to user controls. Tony said less, let's build a user control first, here, use a simple login user control to make a demonstration. First look at the front desk code of the user control (LoginoutControl.ascx file):

<% @ Control Language = "c #" AutoEventWireup = "false" Codebehind = "LogInOutControl.ascx.cs" Inherits = "ZZ.LogInOutControl" TargetSchema = "http://schemas.microsoft.com/intellisense/ie5"%> < Table ID = "Table1" Style = "font-size: 9pt; width: 183px; height: 125p" cellspacing = "1" cellpadding = "1" width = "183" align = "center" border = "1"> < Tr> User: Password:

We put two Label, two TextBox, two Button and an HTML table. The next is to add a code for the loginoutcontrol.ascx.cs file. First define a delegate, where the Loginouteventargs class is inherited from Eventargs class, public delegate Void LoginoutClickHandler (Object Sender, Loginouteventargs E); I think this delegate is more appropriate outside the LoginoutControl class. Next, the LoginoutClick event is declared as the control, as follows:

Public Event LoginoutClickHandler LoginoutClick; In addition to better use attributes, add Language enumeration,

Private language language; Of course, the outside is accessed through the Public Language LG {Get; Set;} property. The purpose is to change or get the display of the current control. Next is to define the control event trigger function OnLoginoutClick, and click the event handler to complete the trigger to the user control event. The full code is as follows:

namespace ZZ {using System; using System.Data; using System.Drawing; using System.Web; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; // define a proxy public delegate void LogInOutClickHandler (object sender , LogInOutEventArgs e); public class LogInOutControl: System.Web.UI.UserControl {protected System.Web.UI.WebControls.Button ButtonLogIn; protected System.Web.UI.WebControls.TextBox TextBoxUserName; protected System.Web.UI.WebControls. TextBox TextBoxPassword; protected System.Web.UI.WebControls.Button ButtonLogOut; protected System.Web.UI.WebControls.Label LabelUser; protected System.Web.UI.WebControls.Label LabelPassword; public event LogInOutClickHandler LogInOutClick; private Language language; // Method PUBLIC VOID CHANGELANGUAGE (LANGUAG = Language;} // Property public language lg {set {if (value! = This.language) {if (value == Language.English) {this.labeluser.text = "User:"; this.labelpassword.text = "Password:"; This.ButtonLogin.Text = "login"; this.buttonlogout.text = "logout";} else {this.labeluser.text = "User:"; this.labelpassword.text = password: "; this.buttonlogin.text = "Login"; this.ButtonLogout.Text = "Logout";}}}} private void page_load (object sender, system.eventargs e) {if (this.labeluser.text == "User:" This.language = Language.english; else this.language = language.Chinese;} private void onlineinoutclick (object sender, loginouteventargs e) {if (loginoutclick! = Null) LoginoutClick (this, e);

} #Region Web Form Designer generated code override protected void OnInit (EventArgs e) {InitializeComponent (); base.OnInit (e);} private void InitializeComponent () {this.ButtonLogIn.Click = new System.EventHandler ( this.ButtonLogIn_Click); this.ButtonLogOut.Click = new System.EventHandler (this.ButtonLogOut_Click); this.Load = new System.EventHandler (this.Page_Load);} #endregion private void ButtonLogIn_Click (object sender, System.EventArgs e) {OnLogInOutClick (this, new LogInOutEventArgs (LogInClickType.LongIn, CustomValidate (this.TextBoxUserName.Text, this.TextBoxPassword.Text)));} private void ButtonLogOut_Click (object sender, System.EventArgs e) {// Code omitted logout OnLogInOutClick (this, new LogInOutEventArgs (LogInClickType.LongOut, true));} // verification function private bool CustomValidate (string userName, string password) {// the code verification is omitted, it is assumed by the return true;}}} defines another file Enumeration and parameter class:

using System; namespace ZZ {public class LogInOutEventArgs: EventArgs {private LogInClickType type; private bool result; public LogInOutEventArgs (LogInClickType type, bool result): base () {this.type = type; this.result = result;} public LogInClickType Type {Get {return this.type;}} // operation result, public bool result {get {return this.result;}}} // Operating type public enum LoginclickType: int {longin, longout} // definition language public enum language {Chinese, English}} Take a look at it in the ASPX page. Create a New Default.aspx page, drag a loginoutcontrol user control to top.

<% @ Register TagPrefix = "uc1" TagName = "LogInOutControl" Src = "LogInOutControl.ascx"%> <% @ Page language = "c #" Codebehind = "Default.aspx.cs" AutoEventWireup = "false" Inherits = "ZZ .Default "%> <% @ import namespace =" zz "%> Webform1 </ title> </ head> <body> <form id =" form1 "method =" post "runat = "Server"> <font face = "Song"> <uc1: loginoutcontrol id = "loginoutcontrol1" runat = "server"> </ uc1: loginoutcontrol> <ask: label id = "labelmsg" runat = "server"> <server> < / asp: label> <ask: DropdownList ID = "DropDownList1" runat = "server" autopostback = "true"> <ask: listitem value = "0" SELECTED = "true"> Chinese </ asp: listItem> <asp: ListItem value = "1"> English </ asp: listitem> </ asp: DropdownList> </ font> </ form> </ body> </ html> Add events and properties in the background code. Although loginoutControl1 is added at the front desk, protected loginoutcontrol loginoutcontrol1 will not be generated in the background code; this statement, I feel very strange, no matter what he first. The LoginoutClick event is then registered in the Page_Load event: this.loginoutControl1.loginoutClick = New LoginoutClickHandler (LoginoutControl1_LoginoutClick);</p> <p>The full code is as follows:</p> <p>using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls ; using System.Web.UI.HtmlControls; namespace ZZ {public class Default: System.Web.UI.Page {protected System.Web.UI.WebControls.Label LabelMsg; protected System.Web.UI.WebControls.DropDownList DropDownList1; protected LogInOutControl LogInOutControl1; private void Page_Load (object sender, System.EventArgs e) {// event registered user control this.LogInOutControl1.LogInOutClick = new LogInOutClickHandler (LogInOutControl1_LogInOutClick);} #region Web form Designer generated code override protected void OnInit (EventArgs e) {InitializeComponent (); base.OnInit (e);} private void InitializeComponent () {this.DropDownList1.SelectedIndexChanged = new System.EventHandler (this.DropDownList1_SelectedIndexChanged); this.Load = new System.EventHandler ( THIS.PAGE_LOAD;} #ENDREGION Private Void Loginou Tcontrol1_loginoutclick (object sender, loginouteventargs e) {switch (e.type) {copy loginclicktype.longin: this.labelmsg.text = "You clicked the login button, the results:" E.Result.toString (); break; cas LogInClickType.LongOut: this.LabelMsg.Text = "you click the logout button, result:" e.Result.ToString (); break;}} private void DropDownList1_SelectedIndexChanged (object sender, System.EventArgs e) {this.LogInOutControl1 .Lg = (language) this.dropdownList1.selectedIndIndex; //this.loginoutcontrol1.changeelanguage ((Language )this.dropdownList1.selectedIndex);}}}</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-22074.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="22074" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.046</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'mkYN_2Bs4H7MLZIeCIRcgcziLz7_2FK0TNTRFdns5c94G9WVLhsO1_2B69r_2Bl8aBCFvOL8HDLNgVsGIpeMpDN1Emmlpw_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>