Asp. NET Tutorial: A method for summarizing foreground code binding background variables

Source: Internet
Author: User
Tags end eval execution expression net opening and closing tags variables string

You often encounter problems with the values of variables in the background code that you want to use (or bind) in the foreground code. There are generally <%= str%> and <%# str%> two ways, here a short summary. If there is any mistake or objection, please advise.

Regard The front desk that is spoken here is usually. aspx file, which refers to the codebehind associated with ASPX, and the file suffix named. aspx.cs; On the other hand, the binding here refers to the user to send access to a page instruction, the server side in the execution of the foreground code has been assigned, and then generate HTML format return The client displays, rather than having been shown to the client, and then goes to the server side to get the corresponding variable through other methods, such as Ajax.

Note: The two files mentioned above are common code-behind (Code-behind) patterns, and there is a code embedding (code-beside, inline) pattern where only aspx files exist and the latter code writes to <script type= " Text/javascript "runat=" ></script> (there are some grammatical differences), which has a slight impact on the issues discussed in this article, because code embedding is declarative code and C#/VB. NET code is compiled into a class together, and code-behind is the declarative code with C#/VB. NET code is translated/compiled several times, so the former is a local and local (partial) relationship between the base class and the derived class, but this only affects the scope of the variable that can be bound (related to modifiers), as mentioned below. The following are examples of code-behind patterns.

In general, background variables (bindings) may be used in three locations in the foreground code:

Server-side control properties or HTML tag properties

in JavaScript code

The position of the HTML display content (that is, the content between the start tag and the end tag, such as <div> here </div> (HTML tags) or <asp:label id= "Label2" runat= "Server" text= " Label > here </asp:Label> (server-side control), which displays the variable as a placeholder where the symbol appears

For the first position, there are some constraints:

(1) The general attribute requirements are string or numeric (some server-side attributes support attributes as data sets);

(2) Not all properties can be bound to variables, some properties such as the Runat property must be a "server" constant, even if the bound string is a server, will cause parser parsing error;

(3) There is a property, he requires the attribute value has constraints (type constraints, such as server-side control requirements TabIndex attribute is short type, or string content has constraints), should also be satisfied at the time of binding, otherwise it may still compile the times wrong;

(4) Also a property, although the property itself has constraints, but even if the bound variable does not meet the constraints, you can compile through, such as the checked property of input, it only checked string is legitimate, but if the string obtained through the binding is not checked, Then these attributes will have their own internal processing mechanism, to ensure the normal use;

(5) Also note that even for the same class of properties, server-side and HTML properties of the processing mechanism is also different, the same is TabIndex (TabIndex), the former if not satisfied, the parser error, the latter ignores this problem.

For the second location, it is generally as long as the background variables that are bound are compatible with the data types in JavaScript.

For the third location, if the binding appears in a location that is not inside the server-side control, there is no constraint, as long as the constant string can appear in a position that can be bound. However, there are constraints to the way that is placed inside the server-side control, which is the <asp:label id= "Label2" runat= "Server" text= "Label" > here </asp:Label>. By summarizing, it concludes four Class server-side control, if the bound code appears between the opening and closing tags of these controls (where the control refers to a layer of nested controls outside the binding code, which is the most inner control surrounding the bound code), there are different display results:

(1) Constrained controls: This type of control requires that its start and end labels contain only the specified child controls, so if a code block appears here, the error is compiled. For example:

<asp:datalist runat= "Server" ></asp:datalist>, between which requires that <ItemTemplate></ItemTemplate> be nested.

(2) non-nested class controls: Such controls, which do not allow internal nesting of other controls or labels, can only be constant strings, which take the contents of the constant string in the start and end tags as his properties. For example, the textbox mentioned above will use the contents of the label as its Text property value.

(3) Nested class controls: Such controls can nest any other control or contain strings, so the string content represented by a bound code block can be displayed normally. such as label controls, panel, and so on.

(4) Data-bound class controls: This type of control is a server-side control provided by ASP.net, and can be bound to a data collection (only the second way it can be done), in addition to the normal variable type.

about whether to enclose quotes: should <%= str%> or <%# str%> be placed in single or double quotes when used in the above three locations? For different locations, the way of handling is different: (specifically please in the following two ways of specific introduction, to be experienced)

(1) for the first position, because JavaScript is weakly typed, it is always true if the binding is quoted as a string, and it is all right, and if the binding is not quoted, it will think it is a numeric type, so if you get a real number, you can, of course, if it's a non-numeric type, will produce a script error, which is the same even for JavaScript assignment constants:

The following are the referenced contents:

var test1 = 123b;//run times wrong
var test2=123;//is correct and is a numeric type
var test3= "123b";//correct, String type

(2) for the second position, it is tested that the quotation marks are always correct for either server-side control properties or HTML tag properties, and if no quotes are used, the two properties are handled differently:

For server-side control properties, if the bound code block is not enclosed in quotes, the compile-time warning message "Verify (asp.net): The attribute value must be quoted before and after" is created, but the corresponding generated HTML attribute has been enclosed in quotes and the correct binding result is obtained. Therefore, the addition of quotes does not affect the use of, but the recommended code for the specification, or add to the good;

For HTML tag Properties, if you do not enclose quotes, you are prompted at compile time to verify (XHTML 1.0 Transitional): a warning that must be enclosed in quotes before and after the attribute value, and that the HTML attribute is not actually quoted. Then, although the attributes do not have the correct binding value behind the quotes, they do not necessarily show the results you want to see. For example, for the value attribute of the input tag, if the bound string is "Hello World", the content displayed in the client's input is actually just a "hello" string, and the property value in effect is a truncated string, the variable It starts with the first non-null character of a string of strings after the attribute (if not quoted), up to the previous character of the next null character (for example, "Hello World", the result will be "good"), so it is necessary to enclose the quotation marks.

(3) for the third position, add and without quotes, the obtained value and its display are unaffected.

Therefore, it is recommended that all binding expressions be quoted as strings and then converted with the corresponding function to get the desired type, depending on the actual requirements.

In addition, the background variables described here are generic, including the following:

Member variable

The return value of a method or property

expression, that is, all the background can be executed code, the resulting value after the run (that is, the background code is written directly in the foreground code, remember to use the fully qualified name or in the background using related namespace)
Data collection

Background variables have some constraints that need to be met:

(1) variable modifier requirements. The variable is either static or an instance field. For the asp.net of the code-behind pattern, the variable described above must be either public or protected type (because it is the relationship between the base class and the derived class), private or internal, and code embedding mode can be accessed by any modifier variables (relationships within a class).

(2) Variable type requirements. Because foreground properties are typically string types, and JavaScript basic types are string, numeric, and Boolean, the corresponding variables should be the same, and if the remaining types are not supported (such as complex types, arrays, reference types, and so on), The foreground gets the string that the ToString () method of the variable was called. Therefore, in the binding time, depending on the situation to see whether the implicit type conversion, if necessary, with the relevant function to cast, to ensure that the foreground can get the correct value. Of course, for a data-bound class control, some of its properties can be data collections, but the binding can only be supported by the following second method.

The above is a number of concepts and basic constraints, these are both ways should be met, the following specific two ways to implement the foreground Code (hereinafter referred to as code block) binding background variables function.

I. <%= str%>

This approach is actually supported by the ASP era, and the ASP outputs the execution results to the customer browser by means of an expression contained in <% and%>, such as:<% =test%> sends the value of the variable test to the client browser. In asp.net, this expression can still be used and can appear in the above three locations in the foreground code, but note that in addition to the general constraints described above, for control properties, you must also be bound to a non-server-side control property. In addition, it only binds the first three variable types mentioned above, and does not support binding data collections. Examples are as follows:

Background code:

The following are the referenced contents:

public partial class WebForm2:System.Web.UI.Page
{
public string getvariablestr;//note modifiers for variables
protected void Page_Load (object sender, EventArgs e)
{
if (! IsPostBack)
{
Getvariablestr = "Hello World from Variable";
}
}
Protected string Getfunctionstr ()//note modifiers for return values
{
Return ' Hello World ' from Function ';
}
}

Foreground code:

The following are the referenced contents:

<title></title>
<script type= "Text/javascript" >
function Fun () {

var str = ' <%= datetime.now%> ';
Foreground location 1, which is bound by the third variable type (also the second way,? Because now is a property)
alert (str);
}
</script>
<body onload= "Fun ()" >
<form id= "Form1" runat= "Server" >
<div>
<input type= "text" value= "<%= getvariablestr%>"/>
<%--foreground position 2, the binding is the member variable--%>
"<%= getfunctionstr ()%>"
<%--foreground position 3, the return value of a method is bound >--%>
</div>
</form>
</body>

Some errors are used:

The first way to bind to properties of a server-side control is that the code is not actually parsed if applied to those server-side properties. Like what:

The following are the referenced contents:

<asp:label id= "Label1" runat= "Server" text= "<%= getvariablestr%>" ></asp:Label>
<asp:textbox id= "TextBox1" runat= "Server" text= "<%= getvariablestr%>" ></asp:TextBox>

The text that is displayed is empty and the TextBox is "<%= getvariablestr%>", so remember that adding such a block of code to the properties of the server-side control will not be parsed, but rather the string as a property value, the Label1. So it's not the desired result. If the quotation marks are not added, the error is compiled, indicating that the server tag cannot contain <% ...%> constructs. ”。

This is the problem with the four types of controls that are displayed in the server-side control, as mentioned in the opening paragraph about putting the binding code in the "HTML display" position quickly. As follows:

The following are the referenced contents:

<asp:label id= "Label1" runat= "Server" > "<%= getvariablestr%>" </asp:Label>
<asp:textbox id= "TextBox1" runat= "Server" > "<%= getvariablestr%>" </asp:TextBox>

Where Label1 belongs to a nested class control, Label1 does show the correct result, the textbox belongs to a nested class control, and the textbox, in this way, generates a compilation error, prompting that "code blocks are not supported in this context." ”

Two. <%# Str%>

ASP.net introduces a new declarative syntax <%#%>. This syntax is the basis for using data binding in an. aspx page, and all data-binding expressions must be included in these characters. This is distinguished from the first method of binding in terms of usage and scope of application.

From where it appears, he can appear in the properties of the server-side control in addition to all the places where the first code block appears.

From the bound variable type, he can also work with the ASP.net data-bound class control to bind the fourth type of "variable" above, the data collection (Dropdownlist,datalist,datagrid,listbox these are data-bound class controls, Data sets include ArrayList (array), Hashtable (HA dilute table, DataView (Data View), DataReader, etc.).

In terms of usage, the DataBind () method is also required in the foreground code, in addition to the <%#%> in the corresponding position, in the background code. The following are examples:

Foreground code:

The following are the referenced contents:

<title></title>
<script type= "Text/javascript" >
function Fun () {

var str = ' <%# datetime.now%> ';

alert (str);
}
</script>
<body onload= "Fun ()" >
<form id= "Form1" runat= "Server" >
<div>
<input type= "text" value= "<%# getvariablestr%>"/><br/>
"<%# getvariablestr%>"
<asp:label id= "Label1" runat= "Server" text= "<%# getvariablestr%>" ></asp:Label>
<%--this way you can bind the properties of a server-side control--%>
<asp:dropdownlist id= "DropDownList1" runat= "server" datasource= ' <%# ArrayList '%> ' >
<%--binds the collection to a data-bound class control, implemented by the DataSource property, to see the contents of the collection in a Drop-down box--%>
</asp:DropDownList>
<asp:datalist id= "DataList1" runat= "server" datasource= ' <%# dt%> ' >
<%---Ditto, binding DataTable data collection?--%>
<ItemTemplate>
<table border= "1" cellpadding= "0" cellspacing= "0" >
<tr>
<td>
<asp:label id= "Label2" runat= "server" text= ' <%# Bind ("row0")%> ' ></asp:Label>
<%--because the bound data collection has multiple columns, and this data-bound class control supports templates,
Therefore, you need to specify the columns and formats you want to bind in the template--%>
</td>
<td>
<%# Eval ("Row1")%>
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
</div>
</form>
</body>

As can be seen, this approach can be used not only to implement (replace) the functionality that <%=%> satisfies, you can also bind server control properties (such as the Label1 above), or bind collection types to supported data-bound class controls. In usage, the foreground code differs from the first in addition to binding data sets on data-bound class controls. In the template for the binding class control, how to use Eval, bind, DataBinder.Eval, and so on, is not discussed in this article, you can refer to the following links to the reference article.

Background code:

The following are the referenced contents:

public partial class WebForm2:System.Web.UI.Page
{
public string getvariablestr;
Public ArrayList ArrayList;
public DataTable DT;
protected void Page_Load (object sender, EventArgs e)
{
if (! IsPostBack)
{
Getvariablestr = "Hello World from Variable";

ArrayList = new ArrayList ();
ArrayList. ADD ("Election item 1");
ArrayList. ADD ("Election item 2");

            dt = new DataTable ();
            dt. Columns.Add ("Row0");
            dt. Columns.Add ("Row1");
            DataRow dr1 = dt. NewRow ();
            Dr1[0] = "1.1";
            Dr1[1] = "1.2";
            DataRow dr2 = dt. NewRow ();
            Dr2[0] = "2.1";
            Dr2[1] = "2.2";
            dt. Rows.Add (DR1);
            dt. Rows.Add (DR2);

Page.DataBind ();
Dropdownlist1.databind ();
Datalist1.databind ();
}
}
}

In the background code, the only difference from the first approach is the need to invoke the DataBind method. Only the DataBind method of the corresponding control is executed. The bindings that use <%#%> in these controls in the foreground code occur (and all the bindings inside the control also occur, such as a control that binds the background data), otherwise the words will not be assigned, but the default null values. Above we use the page DataBind method, then the entire page all bindings will execute. Of course, if we only perform DataList1 or DropDownList1 databind methods, then only the binding of the corresponding control will occur. Note that what is said here needs to be done DataBind includes display and implicit execution, and some data-bound class controls, when they are bound to a data source control through the DataSourceID property, perform the binding by implicitly calling the DataBind method. Then there is no need to display the call again.

The difference between the two:

On both binding methods, their constraints are essentially the same, and they all require matching attributes to appear where they can appear. The latter is more widely used, especially in support of server-side controls and bound data collections. Background code, the latter need to invoke DataBind to complete the binding, the former does not have this requirement. The main difference here is the difference between the execution mechanism:<%=...%> is called when the program executes (should be done during the RenderControl event of the page, That is, usually we can see the background code after the execution and then go to the foreground code in the assignment binding), and <%# ...%> is called after the DataBind () method, and once DataBind () is invoked, its corresponding control binds the variable, so Please note that if you modify the variable after DataBind (), then the binding is not the most recent value, which requires you to DataBind () after the assignment of the variable is completed. In fact, in both ways, it can be run in VS by setting breakpoints to see where the binding assignment of the two occurs.

The remaining questions:

1. Do not know why can not get to the internal modified variable?

Source: http://www.cnblogs.com/lerit/archive/2010/10/22/1858007.html

This article copyright to the author and blog Park, Welcome to reprint, but without the consent of the author must retain this paragraph, and in the article page obvious location to the original connection, otherwise retain the right to pursue legal responsibility.



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.