ASP. NET frontend how to call the variables defined in the background, that is, Data Binding

Source: Internet
Author: User

You may often encounter the problem of using (or binding) the variable value in the background code in the front-end code. Generally, there are two methods: <% = STR %> and <% # STR %>. Here is a brief summary. If you have any errors or objections, please kindly advise.

On the one hand, the front-end is common. aspx file. The background refers to the codebehind associated with Aspx. The file suffix is. aspx. CS; on the other hand, binding here means that after a user sends a command to access a page, the server has assigned a value to the front-end code during execution, after the HTML format is generated, it is returned to the client for display, instead of being displayed to the client. Then, you can use other methods (such as Ajax) to obtain the corresponding variables on the server.

Note: The two files mentioned above are in the code-behind mode and the code-beside (Inline) mode, that is, only one aspx file exists, the background code is written into the <SCRIPT type = "text/JavaScript" runat = "server"> </SCRIPT> file (there are some syntax differences ), this has a slight impact on the issues discussed in this article, because code embedding is declarative code and C #/VB.. Net code is compiled together into a class, while the code is hidden, the declarative code and C #/VB.. Net code is separated several times for translation/compilation. Therefore, the former is the relationship between local and local (partial), and the latter is the relationship between the base class and the derived class, however, this only affects the range of variables that can be bound (related to modifiers. The following uses the code hiding mode as an example.

Generally, backend variables may be used (bound) in three front-end code locations:

Server-side control attributes or HTML tag attributes

JavaScript code

The location of the HTML display content (that is, the content between the start tag and the end tag, for example, <div> here </div> (HTML Tag) or <asp: label id = "label2" runat = "server" text = "label"> here </ASP: Label> (server-side control ), it is used as a placeholder to display variables at the position where the symbols appear)

For the first position, there are some constraints:

(1) The general attribute requirements are string or numeric. (Some server attributes support data sets );

(2) Not all attributes can be bound to variables. For example, the runat attribute must be a constant of "server". Even if the bound string is a server, an error occurs during analyzer analysis;

(3) There is an attribute that requires the attribute value to be constrained (type constraints, for example, the server-side control requires that the tabindex attribute be of the short type, or the string content is constrained ), it should also be met during binding; otherwise, an error may still be reported during compilation;

(4) another property. Although the property itself has constraints, it can be compiled even if the bound variable does not meet the constraints, such as the checked attribute of input, only the checked string is valid, but if the string obtained by binding is not checked, these attributes will have their own internal processing mechanism to ensure normal use;

(5) Pay attention to the fact that, even for the same class of attributes, the processing mechanisms of the server side and the HTML attributes are also different. The same is tabindex (tabindex). If the former does not meet the requirements, the analyzer is incorrect, the latter ignores this issue.

For the second position, it is generally only required that the bound background variable is compatible with the Data Type in JavaScript.

For the third position, if the binding position does not exist in the server-side control, there is no constraint. As long as it is a constant string that can appear, it can be bound. However, for the control placed inside the server, that is, the <asp: Label id = "label2" runat = "server" text = "label"> here </ASP: label>, there are constraints. The summary is summarized into four types of server-side controls. If the bound code appears between the start and end labels of these controls (the control mentioned here, if the bound code is surrounded by multiple layers of nested controls, it refers to the inner control of the bound code), with different display results:

(1) Constrained controls: these controls require that their start and end labels only contain the specified child controls. Therefore, if a code block appears here, a compilation error occurs. For example:

<Asp: datalist runat = "server"> </ASP: datalist>. The <itemtemplate> </itemtemplate> must be nested between them.

(2) Non-nested controls: such controls cannot be embedded with other controls or labels, but can only be constant strings, it uses the constant string content in the start tag and end tag as its attribute. For example, the textbox mentioned above uses the content between tags as its text attribute value.

(3) nested controls: these controls can be nested with any other controls or contain strings. Therefore, the string content represented by the bound code block can be displayed normally. Such as label control and panel.

(4) data binding controls: these controls are Asp. the server-side controls provided by. Net can be bound to either a common variable type or a data set (only implemented in the second method below ).

Quotation marks: Should <% = STR %> or <% # STR %> be placed in single or double quotation marks when using the preceding three positions? For different locations, the processing method is different: (Please refer to the following two methods for details)

(1) For the first position, because Javascript is weak, it is always correct to treat it as a string if quotation marks are added during binding; if no quotation marks are added during binding, it will be considered as a numerical value. If the obtained value is a real value, of course, if it is not a numeric value, a script error will be generated, this is the same even when a constant is assigned to javascript:

 

Reference content is as follows:

VaR test1 = 123b; // an error is reported during running.
VaR Test2 = 123; // correct, which is a numeric value
VaR test3 = "123b"; // correct, string type
 

 

(2) For the second position, the quotation marks are always correct for both the server-side control attributes and the HTML tag attributes. If no quotation marks are added, the two attributes are processed in different ways:

For server-side control attributes, if the bound code block is not enclosed by quotation marks, the system prompts "authentication (Asp. net): The warning information must be enclosed by quotation marks before and after the feature value. However, after being generated as HTML, the corresponding HTML attribute has been enclosed by quotation marks and the correct binding result is obtained, therefore, adding quotation marks does not affect the use of the Code. However, it is recommended that you add the standard code as well;

For HTML tag attributes, if no quotation marks are added, the warning message "verification (XHTML 1.0 transitional): must be enclosed by quotation marks" is displayed during compilation, in addition, HTML attributes are not enclosed by quotation marks. Although the correct binding value is not followed by quotation marks, the expected results may not be displayed. For example, for the Value Attribute of the input tag, if the bound string is "Hello world from variable", the content displayed in the client's input is actually a "hello" string, the valid property value is a truncated string. It starts from the first non-null character of a string (if no quotation marks are added) after the attribute, as of the first character of the next null character (for example, for "hello World", the result will be "hello"), so quotation marks are required.

(3) For the third position, adding and without quotation marks will not affect the obtained value and display.

Therefore, it is recommended that all binding expressions be enclosed in quotation marks and obtained as strings. Then, convert the expressions based on actual needs and use the corresponding functions to obtain the desired type.

In addition, the background variables mentioned here are generic, including:

Member variables

Return Value of a method or attribute

Expression, that is, the value obtained after running all the code that can be executed in the background (that is, the background code is directly written in the foreground code, remember to use a fully qualified name or using-related namespace in the background)
Data Set

Background variables have some constraints that must meet:

(1) variable modifier requirements. The variables are static or instance fields. For ASP. net, the variables described above must be of the public or protected type (because it is the relationship between the base class and the derived class), neither private nor internal can, in the Code embedding mode, any modifier variables can be accessed (the internal relationship of a class ).

(2) variable type requirements. Because the foreground attribute is generally a string type, and the basic JavaScript type is string type, number type, and boolean type, the corresponding variables should also be in these ways, if other types are not supported (such as complex types, arrays, and reference types), the front-end obtains the string obtained by calling the tostring () method of the variable. Therefore, when binding, check whether implicit type conversion can be performed based on the situation. If necessary, use related functions to force conversion to ensure that the foreground can obtain the correct value. Of course, for data binding controls, some of its attributes can be data sets, but the binding can only be supported in the second way below.

The above are some concepts and basic constraints that should be met in both ways. The following describes two methods to implement the front-end code (called code block) bind background variables.

1. <% = STR %>

This method is actually supported in the ASP era. asp outputs the execution result to the client browser through expressions contained in <% and %>, such: <% = test %> is to send the value of the variable test to the client browser. In ASP. net, this expression can still be used and appear in the preceding three positions of the front-end Code. However, note that in addition to the preceding general constraints, for the control attributes, it must also be the property bound to a non-server-side control. In addition, it can only bind the first three variable types mentioned above, and does not support binding data sets. Example:

Background code:

 

Reference content is as follows:

Public partial class webform2: system. Web. UI. Page
{
Public String getvariablestr; // variable Modifier
Protected void page_load (Object sender, eventargs E)
{
If (! Ispostback)
{
Getvariablestr = "Hello world from variable ";
}
}
Protected string getfunctionstr () // note the modifier of the returned value
{
Return "Hello world from function ";
}
}
 

 

Front-end code:

 

Reference content is as follows:

<HTML xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> </title>
<SCRIPT type = "text/JavaScript">
Function fun (){

VaR STR = '<% = datetime. Now %> ';
// The front-end location 1 is bound to the third variable type (which is also the second method ,? Because now is an attribute)
Alert (STR );
}
</SCRIPT>
</Head>
<Body onload = "Fun ()">
<Form ID = "form1" runat = "server">
<Div>
<Input type = "text" value = "<% = getvariablestr %>"/>
<% -- Foreground Location 2, bound with a member variable -- %>
"<% = Getfunctionstr () %>"
<% -- Foreground location 3, bound to the return value of a method> -- %>
</Div>
</Form>
</Body>
</Html>
 

 

Incorrect use:

The reason why the first binding method is used for non-server-side control attributes is that the Code is not actually parsed if it is applied to these server-side attributes. For example:

 

Reference content is as follows:

<Asp: Label id = "label1" runat = "server" text = "<% = getvariablestr %>"> </ASP: Label>
<Asp: textbox id = "textbox1" runat = "server" text = "<% = getvariablestr %>"> </ASP: textbox>
 

 

The displayed label1 text is empty, while the textbox Chinese text is "<% = getvariablestr %>", so remember to add such a code block to the properties of the server-side control, this string is directly used as the property value instead of being parsed, so it is not the desired result. If no quotation marks are added, a compilation error is displayed, prompting "the server tag cannot contain <%... %> constructor .".

Here, we will discuss how to display the four types of controls in the server-side controls when binding code to "HTML display content location. As follows:
 

 

Reference content is as follows:

<Asp: Label id = "label1" runat = "server"> "<% = getvariablestr %>" </ASP: Label>
<Asp: textbox id = "textbox1" runat = "server"> "<% = getvariablestr %>" </ASP: textbox>
 

 

Label1 is a nested control, and label1 does display the correct result. textbox is a non-nested control. If textbox is used in this way, a compilation error occurs, the prompt "this context does not support code blocks."

Ii. <% # STR %>

ASP. NET introduces a new declaration syntax <% # %>. This syntax is the basis for using data binding on the. ASPX page. All data binding expressions must be included in these characters. Here, we will distinguish it from the first binding method in terms of usage and scope of application.

In addition to all the positions where the first code block appears, it can also appear in the properties of the server-side control.

From the perspective of the bound variable type, it can also work with ASP. NET data binding controls, to bind the fourth "variable" Type above, is the data set (dropdownlist, datalist, DataGrid, ListBox, these are data binding controls, data sets include arraylist (array), hashtable (HA table, dataview (data view), and datareader ).

In terms of usage, besides <% # %> In the front-end code, you also need to use the databind () method in the background code. The following are examples:

Front-end code:

 

Reference content is as follows:

<HTML xmlns = "http://www.w3.org/1999/xhtml">
<Head>
<Title> </title>
<SCRIPT type = "text/JavaScript">
Function fun (){

VaR STR = '<% # datetime. Now %> ';

Alert (STR );
}
</SCRIPT>
</Head>
<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 method can bind server-side control attributes -- %>
<Asp: dropdownlist id = "dropdownlist1" runat = "server" datasource = '<% # arraylist %>'>
<% -- Bind the set to the Data Binding class control through the datasource attribute, so that the content in the set is displayed in the drop-down box -- %>
</ASP: dropdownlist>
<Asp: datalist id = "datalist1" runat = "server" datasource = '<% # DT %>'>
<% -- Same as above, is a datatable Data Set bound? -- %>
<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 set has multiple columns, and this data binding class control supports templates,
Therefore, you must specify the columns to be bound and the format in the template -- %>
</TD>
<TD>
<% # Eval ("row1") %>
</TD>
</Tr>
</Table>
</Itemtemplate>
</ASP: datalist>
</Div>
</Form>
</Body>
</Html>
 

 

We can see that this method can be used not only to implement (replace) <% =... %> You can also bind the server control attributes (such as label1), or bind the set type to the supported data binding controls. In terms of usage, the front-end code is different in addition to binding a data set to a data binding control. Other usage is no different from the first one. In the template for binding class controls, how to use Eval, bind, databinder. Eval, etc. is not discussed in this article. You can refer to the reference article of the following link.

Background code:

 

Reference content is as follows:

Public partial class webform2: system. Web. UI. Page
{
Public String getvariablestr;
Public arraylist;
Public datatable DT;
Protected void page_load (Object sender, eventargs E)
{
If (! Ispostback)
{
Getvariablestr = "Hello world from variable ";

Arraylist = new arraylist ();
Arraylist. Add ("Select? Item? 1 ");
Arraylist. Add ("Select? 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 method is that you need to call the databind method. Only when the databind method of the corresponding control is executed will binding <% # %> be used in these controls in the front-end code (and all bindings inside the control will also occur, for example, if another control is nested to bind background data), otherwise it will not be assigned a value, but will be null by default. We used the databind method of the page above, so all bindings to the whole page will be executed. Of course, if we only execute the databind method of datalist1 or dropdownlist1, only binding the corresponding control will happen. Note that the execution of databind includes display and implicit execution. Some data binding controls are used when they are bound to the data source control through the performanceid attribute, the binding is executed by calling the databind method implicitly. In this case, you do not need to display the call again.

Differences:

In the two binding methods, their constraints are basically the same, both of which must match the attributes and appear where they can appear. The latter is widely used, especially for server-side controls and binding data sets. In terms of background code, the latter needs to call databind to complete binding. The former does not have this requirement. The difference between the two is as follows: <% =... %> is called during program execution (it should be completed during the rendercontrol event on the page, that is, the background code we can see is usually executed and then assigned to the foreground code), and <% #... %> is called after the databind () method. Once databind () is called, its corresponding control is bound to a variable. Therefore, note that if () then modify the variable, so the bound value is not the latest value. This requires you to complete the variable assignment and then go to databind (). In fact, the running process of these two methods can be viewed in vs by setting breakpoints to see when the binding values of the two methods occur.

 

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.