Asp. Separation of program architecture and program code in net

Source: Internet
Author: User
Tags html tags mixed php file tagname
Asp.net| Program

A year ago, when I got a PHP program called Twig, was immediately impressed by the author OOP programming ideas, it is difficult to imagine Twig all the functions (calendar, mail, personalization) in a php file (index.php3) executed, This is because the author used the idea of separating the program code from the page frame, but I also see that despite the great efforts of the author, the program does not really separate the code from the architecture because of the limitations of PHP. Index.php3 This main file because there are too many functions to perform, so its require module file is quite many, to make the whole file still seems very messy, I am ignorant, then spent half a month time, just really understand the framework of the program, analysis of the pain of the code, no one can know AH (sadly tears ......)。

The Twig program has a big impact on my subsequent programming, but even this kind of work still doesn't get rid of the mix of program code and HTML code.

The separation of program code from page architecture is the dream of web programmers for many years. Before the asp.net appeared, whether ASP, PHP or JSP, program code and HTML code are mixed together, this approach, although in the early days of the Web technology was praised, but over time, its drawbacks are more and more obvious, when the program code is very long, the HTML code and its mixed , the readability of the program becomes so poor that it is impossible to distinguish the page architecture that the program really wants to represent.

The new technology asp.net the code by means of codebehind, user control, and custom controls (named Control). This is a remarkable improvement, and you can see how clear the structure of the ASP.net program is after separating the code in this article.

Flying knives here to show you their specific implementation methods, we first look to achieve the function.

For the sake of understanding, the page designed here is simpler, the page is divided into three main parts, the head contains a AdRotator control (for display ads) and a label control (used to display the current ad link address); The middle is a landing page, including two TextBox controls ( Used to enter a username and password respectively, a label control (showing whether the login was successful) and a Button control (as the Submit button); The bottom contains two label controls (the current user name and user rights are displayed, respectively).

Familiar with ASP.net's friends, you'll soon realize that the head because the AdRotator control is used, there must be a onadcreated event to display the link in the Label control, and the middle is bound to have a onclick event handling because it is a submit button using the button control.

1 codebehind


First we will see how to use the Codebehind method to achieve the separation of Code and page architecture, the following source program is the main asp.net program--example1.aspx:

<% @ Page src= "Cs\eventhandle.cs" inherits= "ASPCN"%>
<title></title>
<body>
<form runat= "Server" >
<asp:panel id= "Header" runat= "Server" >
<asp:adrotator id= "ad" advertisementfile= "Adbanners\ad.xml" borderwidth= "0" onadcreated= "AdCreated" runat= " Server "/><br>
Current AD Links: <asp:label id= "Lbladtext" forecolor= "Red" runat= "Server"/>
</asp:Panel>

<asp:panel id= "Logon" runat= "Server" >
<table>
&LT;TR&GT;&LT;TD colspan= "2" align= "Center" ><b> Landing window </b></td></tr>
&LT;TR&GT;&LT;TD colspan= "2" align= "center" ><asp:label id= "lblmsgshow" forecolor= "Red" runat= "Server"/> </td></tr>
<tr><td> User name: </td><td><asp:textbox id= "Tbusername" runat= "Server"/></td></ Tr>
<tr><td> Password: </td><td><asp:textbox id= "tbpasswd" textmode= "Password" runat= "Server"/> </td></tr>
<tr><td><asp:button id= "btnsubmit" text= "Landing" runat= "Server"/></td></tr>
</table>
</asp:Panel>

<asp:panel id= "Footer" runat= "Server" >
User name: <asp:label id= "Lblusername" font-name= "Arial" forecolor= "Red" text= "visitor" runat= "Server"/>

Permissions: <asp:label id= "Lblpurview" font-name= "Arial" text= "None" forecolor= "Red" runat= "Server"/>
</asp:Panel>
</form>
</body>

Routines, you can clearly see that the program does not contain any C #, VB, JavaScript to handle the onadcreated and onclick events, but this program can be used normally (figure 2-1 and Figure 2-2). This is the result of using Codebehinde, and event handling has been transferred to other programs to define execution. Please note the information in the first line of this example:

<% @ Page src= "Cs\eventhandle.cs" inherits= "ASPCN"%>

Generally in the ASP.net program, the page instruction is set in what language the program should use (using the language attribute), and in this case the language attribute is not present, but instead there are two new page properties: Src and inherits. The SRC attribute setting event handles the real code location, and the Inherits property sets the class name to be introduced. You can see that the file that defines the event handling in this example is EventHandle.cs, and let's look at what it does:

Using System;
Using System.Data;
Using System.Data.SqlClient;
Using System.Web;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Using System.Web.UI.HtmlControls;
public class Aspcn:page
{
To declare a control that appears in a Web Form
Public Label lbladtext,lblusername,lblpurview,lblmsgshow;
Public TextBox tbusername,tbpasswd;
Public Button btnsubmit;
public AdRotator AD;

private string strconnstring = "server= (local) \\FEIDAO;DATABASE=ASPCN; Trusted_connection=yes ";

Handling AdRotator Control Build Events
public void adcreated (Object Src,adcreatedeventargs e)
{
Lbladtext.text = E.alternatetext;
}

public void Submit_click (Object Sender,eventargs e)
{
SqlConnection myconn = new SqlConnection (strconnstring);
MyConn.Open ();
String Strusername,strpassword,strselect;
strUserName = Tbusername.text;
strpassword = Tbpasswd.text;
Strselect = "SELECT * from Bbs_user where id= '" +strusername+ "' and Password= '" "+strpassword+" ";
SqlCommand Mycomm = new SqlCommand (strselect,myconn);
SqlDataReader dr = Mycomm.executereader ();
if (Dr. Read ())
{
Landing success
Lblmsgshow.text = "landing success";
Lblusername.text = dr["id"]. ToString ();
Lblpurview.text = dr["Purview"]. ToString ();
}
Else
{
Landing not successful
Lblmsgshow.text = "Landing unsuccessful";
}
Dr. Close ();
Myconn.close ();
}
}

Event handling is defined in a class (in this case, ASPCN, note case), and because it needs to be associated with Web Forms, this class must also inherit the page class.

Analysis of the program, you can see that the process of the event in the program is the same as the normal code is not separated from the program is the same, and there is no particular place. (I have already given the relevant comments in the program, I believe that the understanding of the procedures to help)

The use of Codebehind technology, you need to write more code, such as the Declaration of Control and so on, perhaps people do not like to write more such code, but we must also see the use of codebehind technology, the main program readability greatly increased. In example1.aspx, it is believed that you will soon be able to distinguish the various parts of the page architecture, and think about whether these architectures can be seen so clearly in other technologies.
(Here's the program only to do demo use, hehe, everybody does not want to catch me any quotes loophole these pigtail yo)

2 user Control (UserControl)
Codebehind technology to truly achieve the separation of code and architecture, a big step forward than the previous technology, but its shortcomings are obvious, such as the main page in the middle of the landing area, if the content of many, HTML display code will still occupy a large area, the program's readability will still be reduced.

Asp. NET also provides a workaround, which is the user control.


User control we can see it as a server control that does not have to be compiled. If you are a control, you are sure to follow the control's methods of use. We look at each panel in example1.aspx as a single control, so the body part of example1.aspx can be reduced to only three rows by using a user control:

<% @ Register tagprefix= "ASPCN" tagname= "Header" src= "Usercontrols/header.ascx"%>
<% @ Register tagprefix= "ASPCN" tagname= "Logon" src= "Usercontrols/logon.ascx"%>
<% @ Register tagprefix= "ASPCN" tagname= "Footer" src= "Usercontrols/footer.ascx"%>
<title></title>
<body>
<form runat= "Server" >
<aspcn:header id= "MyHeader" runat= "Server"/>
<aspcn:logon id= "Mylogon" runat= "Server"/>
<aspcn:footer id= "Myfooter" runat= "Server"/>
</form>
</body>

The execution of this program is the same as the result of using codebehind technology, but now the ASP.net program is easier to distinguish between page architectures.

<aspcn:header id= "MyHeader" runat= "Server"/>
<aspcn:logon id= "Mylogon" runat= "Server"/>
<aspcn:footer id= "Myfooter" runat= "Server"/>

This three lines of code, using three user controls, so little code everyone can clearly see the page is divided into three parts.

To use a user control you must use the Register directive, the TagPrefix attribute definition is a namespace name to ensure that it is unique on this page; The TagName property is an alias that defines a class (class). Because the user control is executed by the CLR as a class to execute, it is necessary to give each user control in this program a unique name so that it can be distinguished; The src attribute is the file name of the user control that is specifically used ( User controls end with. ascx.

The user control is used like a normal server control:
<namespace:class ... runat= "Server"/>
namespace represents the namespace defined, class is the corresponding name, and the specific examples are:
<aspcn:logon id= "Mylogon" runat= "Server"/>

The following are the specific contents of the user control used in the display program for the user control:

Header.ascx (header user control)

<script language= "C #" runat= "Server" >
private void AdCreated (Object Src,adcreatedeventargs e)
{
Lbladtext.text = E.alternatetext;
}
</script>
<asp:adrotator id= "ad" advertisementfile= ". \adbanners\ad.xml "borderwidth=" 0 "onadcreated=" adcreated "runat=" Server "/><br>
Current AD Links: <asp:label id= "Lbladtext" forecolor= "Red" runat= "Server"/>

Logon.ascx (logon user control)

<% @ Import namespace= "System.Data"%>
<% @ Import namespace= "System.Data.SqlClient"%>
<script language= "C #" runat= "Server" >
protected string strconnstring = "server= (local) \\FEIDAO;DATABASE=ASPCN; Trusted_connection=yes ";
Defining the properties of a UserControl
public string UserName
{
Get
{
return tbusername.text;
}
Set
{
Tbusername.text = value;
}
}
public string Password
{
Get
{
return tbpasswd.text;
}
Set
{
Tbpasswd.text = value;
}

}

Event handling
private void Submit_click (Object Sender,eventargs e)
{
SqlConnection myconn = new SqlConnection (strconnstring);
MyConn.Open ();
String Strusername,strpassword,strselect;
strUserName = Tbusername.text;
strpassword = Tbpasswd.text;
Strselect = "SELECT * from Bbs_user where id= '" +strusername+ "' and Password= '" "+strpassword+" ";
SqlCommand Mycomm = new SqlCommand (strselect,myconn);
SqlDataReader dr = Mycomm.executereader ();
if (Dr. Read ())
{
Landing success
Lblmsgshow.text = "landing success";
session["UserName"] = dr["id"]. ToString ();
session["purview"] = dr["Purview"]. ToString ();
}
Else
{
Landing not successful
Lblmsgshow.text = "Landing unsuccessful";
}
Dr. Close ();
Myconn.close ();
}
</script>
<table>
&LT;TR&GT;&LT;TD colspan= "2" align= "Center" ><b> Landing window </b></td></tr>
&LT;TR&GT;&LT;TD colspan= "2" align= "center" ><asp:label id= "lblmsgshow" forecolor= "Red" runat= "Server"/> </td></tr>
<tr><td> User name: </td><td><asp:textbox id= "Tbusername" runat= "Server"/></td></ Tr>
<tr><td> Password: </td><td><asp:textbox id= "tbpasswd" textmode= "Password" runat= "Server"/> </td></tr>
<tr><td><asp:button id= "btnsubmit" text= "Landing" runat= "Server"/></td></tr>
</table>

Footer.ascx (Footer user control)

<script language= "C #" runat= "Server" >
private void Page_Load (Object Src,eventargs E)
{
if (session["UserName"]!=null)
{
Lblusername.text = (string) session["UserName"];
Lblpurview.text = (string) session["purview"];
}
}
</script>
User name: <asp:label id= "Lblusername" font-name= "Arial" forecolor= "Red" text= "visitor" runat= "Server"/>

Permissions: <asp:label id= "Lblpurview" font-name= "Arial" text= "None" forecolor= "Red" runat= "Server"/>

Each control contains its own display code and the corresponding program code.

We can make some commonly used functions as a fixed user control, we can use it when we need it without using annoying crtl+c,ctrl+v to "copy", "Paste" a long pile of code.

The user control not only separates the program code from the page structure, but also increases the reusability of the code.

3 Customizing controls (custom control)

User controls are a good choice, but because each user control is an ascx file, when the controls are numerous, they are used more cluttered. At this point we would like to have some of the more similar controls integrated, in the program only need to quote once, then all done. It's a good idea, and we're going to make it a little more professional: "Import multiple classes (class) into the same namespace (namespace)." Oh, how, this sentence is not a bit familiar? Let's go check the definition of the server control, is not found this sentence is ...

We'll touch on how to write the server control below. Writing the server control is not an easy thing to do, it needs to be right. NET platform has a relatively deep understanding, suitable for advanced users, so I will not specifically describe the server control writing steps (to be careful about this, must write a book). Please compare the difference between the custom control source code and the user control to make some general understanding:

Using System;
Using System.Data;
Using System.Data.SqlClient;
Using System.Drawing;
Using System.Web;
Using System.Web.UI;
Using System.Web.UI.WebControls;
Namespace ASPCN
{
First, header.
public class Header:control,inamingcontainer
{
Private AdRotator AD;
Private Label Lbladtext;

protected override void CreateChildControls ()
{
Add AdRotator AD Control
AD = new AdRotator ();
Ad. AdvertisementFile = "Adbanners/ad.xml";
Ad. BorderWidth = 0;
Ad. AdCreated + = new Adcreatedeventhandler (this. onadcreated);
This. Controls.Add (AD);


This. Controls.Add (New LiteralControl ("<br>" + "current ad link as:"));
Add Label control
Lbladtext = new Label ();
Lbladtext.forecolor = color.red;
This. Controls.Add (Lbladtext);
}
private void onadcreated (Object Sender,adcreatedeventargs e)
{
This.lblAdText.Text = E.alternatetext;
}
}
And then the logon.
public class Logon:control,inamingcontainer
{
private string strconnstring = "server= (local) \\FEIDAO;DATABASE=ASPCN; Trusted_connection=yes ";
Private Label lblmsgshow;
Private TextBox tbusername,tbpasswd;
Public String UserName
{
Get
{
return tbusername.text;
}
Set
{
Tbusername.text = value;
}
}

protected override void CreateChildControls ()
{
Add HTML tags
This. Controls.Add (New LiteralControl ("<table><tr><td colspan=\" 2\ "align=\" center\ "><b> landing window </b></td></tr> <tr><td colspan=\ "2\" align=\ "Center\" >));
Add Msgshow Label control
Lblmsgshow = new Label ();
Lblmsgshow.forecolor = color.red;
This. Controls.Add (lblmsgshow);
This. Controls.Add (New LiteralControl ("</td></tr><tr><td> username:</td><td>"));
Adding username and passwd textbox controls
Tbusername = new TextBox ();
This. Controls.Add (Tbusername);
This. Controls.Add (New LiteralControl ("</td></tr><tr><td> password:</td><td>"));
TBPASSWD = new TextBox ();
Tbpasswd.textmode = Textboxmode.password;
This. Controls.Add (TBPASSWD);
This. Controls.Add (New LiteralControl ("</td></tr><tr><td>"));
Add Btnsubmit Button control
Button btnsubmit = New button ();
Btnsubmit.text = "Landing";
Btnsubmit.click + = new EventHandler (this. Submit_click);
This. Controls.Add (btnsubmit);
This. Controls.Add (New LiteralControl ("</td></tr></table>"));
}
Show complete
private void Submit_click (Object Sender,eventargs e)
{
SqlConnection myconn = new SqlConnection (strconnstring);
MyConn.Open ();
String Strusername,strpassword,strselect;
strUserName = Tbusername.text;
strpassword = Tbpasswd.text;
Strselect = "SELECT * from Bbs_user where id= '" +strusername+ "' and Password= '" "+strpassword+" ";
SqlCommand Mycomm = new SqlCommand (strselect,myconn);
SqlDataReader dr = Mycomm.executereader ();
if (Dr. Read ())
{
Landing success
This.lblMsgShow.Text = "landing success";
}
Else
{
Landing not successful
This.lblMsgShow.Text = "Landing unsuccessful";
}
Dr. Close ();
Myconn.close ();
}
}
and finally, footer.
public class Footer:control,inamingcontainer
{
private string _username,_purview;

public string UserName
{
Get
{
return _username;
}
Set
{
_username = value;
}
}

public string Purview
{
Get
{
return _purview;
}
Set
{
_purview = value;
}
}

Public Footer ()
{
_username = "Visitor";
_purview = "None";
}

protected override void CreateChildControls ()
{
This. Controls.Add (New LiteralControl ("Username:"));
Label Lblusername = new label ();
Lblusername.forecolor = color.red;
LblUserName.Font.Name = "Arial";
Lblusername.text = this. UserName;
This. Controls.Add (Lblusername);
This. Controls.Add (New LiteralControl ("nbsp;"));

This. Controls.Add (New LiteralControl ("Permission:"));
Label Lblpurview = new label ();
Lblpurview.forecolor = color.red;
LblPurview.Font.Name = "Arial";
Lblpurview.text = this. Purview;
This. Controls.Add (Lblpurview);
}
}
}

The above and the program are the features that will need to be implemented, all imported into the custom control. As you can see in the program, there are three classes (Header,logon,footer) in the ASPCN namespace, which is exactly the three body part of the schema.

To use a custom control, you must also compile the original code.

Csc/t:library/out:aspcn.dll/r:system.data.dll,system.web.dll,system.drawing.dll CustomControls.cs

C # program compiler instruction usage, I also no longer repeat here. Note that the compiled file name must be the same as the name of the namespace in the control.

The compiled DLL is still not available and we have to put it in. NET platform, the bin directory (which, if it does not exist, can be established by itself) holds all the custom controls and components used in the current virtual directory,--/bin. When the CLR executes the ASP.net program, it automatically searches for files in this directory to find the namespace, Class, and assembly that match the ASP.net program.

When we put the compiled aspcn.dll into the/bin directory, the server control that we wrote is ready to use.
(It is important to declare that the footer control does not change with the session content as the previous program does, because you cannot use variables such as session to write the server control to communicate between two classes.) However, you can use the normal operation of the server control methods to manipulate the corresponding properties to achieve the same effect, here to save the layout, not used
Let's take a look at the program content of the main Web form:

<% @ Register tagprefix= "ASPCN" namespace= "ASPCN" assembly= "ASPCN"%>
<title></title>
<body>
<form runat= "Server" >
<aspcn:header id= "MyHeader" runat= "Server"/>
<aspcn:logon id= "Mylogon" runat= "Server"/>
<aspcn:footer id= "Myfooter" runat= "Server"/>
</form>
</body>

It's quite simple and clear.
References to our custom controls are also fairly concise, with only the TagPrefix, Namespace, assembly attributes of the Register directive set to ASPCN.

At this point, ASP. NET three kinds of code and page architecture separation method has been introduced.

Three methods have advantages and disadvantages, I prefer to use user control with Codebinde technology, because they do not need to compile, relatively easier to use, if you want to protect your code, the custom control is certainly your best choice.

I hope this article will help you with your programming.



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.