ASP. NET 3.5 core programming learning notes (18): Data Binding expressions

Source: Internet
Author: User

Simple data binding

The data binding expression is the executable code of the <%... %> package, prefixed. It can be managed programmatically through databoundliteralcontrol instances.

The data binding expression usually obtains data from the data source, but it does not mean that it must obtain data from the data source. As long as the bound data is returned, any executable code is acceptable. It performs computation only when the databinding event of the control is triggered.

Example: <asp: Label runat = "server" text = '<% # datatime. Now %>'/>

If you want to use quotes for an expression, select single quotes.

The data binding expression defined on the page is calculated after databind is called. You can call the databind method of the page object or the databind method of the specified control. If you call a page object, call the databind method that defines all controls on the page recursively. If you do not call databind, <% #... %> is never calculated.

The data binding expression is suitable for updating the properties of the current control based on other controls on the page and writing them completely in declaration mode.

<asp:DropDownList ID="SelColors" runat="server" AutoPostBack="True">
<asp:ListItem>Orange</asp:ListItem>
<asp:ListItem>Green</asp:ListItem>
<asp:ListItem>Red</asp:ListItem>
<asp:ListItem>Blue</asp:ListItem>
</asp:DropDownList>
<asp:Label runat="server" ID="lblColor" Text='<%# "<b>You Selected:</b>" + SelColors.SelectedValue %>' />

Note: Expressions in <% #... %> can be a combination of methods, constants, and attributes, as long as the final result matches the type of the bound attribute. The expression needs to be sent back and the databind method is called. Therefore, we set autopostback to true, and call the page or tag databind method to trigger the refresh process.

protected void Page_Load(object sender, EventArgs e)
{
DataBind();
}

Consider the following code:

ForeColor='<%# "orange" %>'
ForeColor="orange"

Only the second statement of the above Code can be parsed normally. The reason is that the data binding expression must ensure that the type of the returned value matches the type of the control property. But there is no problem using a plain text constant string because the page parser recognizes this expression. If you need the parser, the appropriate type conversion code will be inserted.

Internal Implementation of Data Binding expressions

What happens if a data binding expression appears on the web page? Consider the following code:

  <asp:label runat="server" id="today" text='<%# DateTime.Now %>' />

Process in the page parser. aspx source code generates a factory method for each server control. The factory method only maps the label name to the class of a server control, the attribute in the tag is converted into the property of the object by assigning values ). In addition, if there is a data binding expression, the parser will add a handler for the databinding event of the current control. The following code shows the execution result of the process:

private Control __BuildControlToday()
{
Label __ctrl = new Label();
this.today = __ctrl;
__ctrl.ID = "today";

__ctrl.DataBinding += new EventHandler(this.__DataBindToday);
return __ctrl;
}

The handler assigns the content of the data binding expression to the corresponding attribute step by step:

public void __DataBindToday(object sender, EventArgs e)
{
Label target;
target = (Label)sender;
target.Text = Convert.ToString(DataTime.Now);
}

If the value of the data binding expression does not match the expected type, a compilation error occurs. If the expected type is string, the parser will use the convert. tostring method to perform standard conversion.

Databinder class

The eval method is an operator dedicated to data binding expressions used to access the public attributes of bound data items. There is no eval method in the page class before ASP. NET 2.0. If it is used directly in the ASP. NET 1. x application, a compilation error is generated. For all versions of ASP. NET, we can use a method with the same function and its name is also Eval, but it comes from another class-databinder.

Through the eval method, we can access the public attributes of the bound data items. However, it should be clarified that what is the public attribute in this context? All classes that implement ienumerable can be bound to controls. A specific class includes a datatable (each data item corresponds to a record logically) and a custom set (each data item corresponds to an instance of the given class ). The eval method queries the object of a data item based on the attribute set of the data item. The object that represents the record will return the description of all fields, while other objects will return their respective public attribute sets.

The databinder class supports the generation and resolution of data binding expressions. The static method Eval is very important. For runtime objects, This method uses reflection to parse and calculate expressions. The general syntax of this method is:

  <%# DataBinder.Eval(Container.DataItem, expression) %>

The container. dataitem expression is used to reference an object. The expressions in this object are calculated. Expression is generally the name of the field to be accessed in the data item object. It can be an expression that includes an index or attribute name. The dataitem attribute represents the objects in the current container context. Generally, the container is the current instance of the Project object.

More concise eval

The original databinder. Eval syntax is simplified in ASP. NET 2.0 and later versions. The code can be written as follows:

<%# Eval(expression) %>

ASP. NET 1.x can only accept the following expressions:

<%# DataBinder.Eval(Container.DataItem, expression) %>

Obviously, ASP. NET 2.0 and later fully support the databinder class.

All codes in the <% #... %> delimiter are specially processed by ASP. NET. After the page is compiled, the call to the eval method is inserted into the source code of the page and exists independently. The following code reveals the internal details:

object o = Eval("lastname");
string result = Convert.ToString(o);

The call result is converted to a string and assigned to the data binding control. Then, the data binding text is inserted into the page Control tree.

With the eval method, the templatecontrol class is extended. The following pseudo code reveals the Internal principles of the method:

protected object Eval(string expression)
{
if(Page == null)
throw new InvalidOperationException(...);
return DataBinder.Eval(Page.GetDataItem(), expression);
}

It can be seen that the eval method is just a closed tool, which is built around the databinder. Eval method. The databinder. Eval method is called by the data items of the current container. The data of the current container is empty before the data binding operation is executed, which is the main difference between eval and databinder. eval.

The eval of templatecontrol is a data binding method, which is only used for the Data Binding operation in the context of the data binding control. Databinder. Eval is a completely free method that can be used anywhere.

Obtain default data items

The getdataitem method of the page class is used in the code of the eval method in the previous demo page. What is this? As mentioned above, the simplified syntax uses a default container. dataitem context object. Getdataitem is the function that returns this object.

Specifically, getdataitem is the end of the stack-based call mechanism (this mechanism tracks the current binding context of the page ). Each control in the control tree is pushed to this stack when its databind method is called. When the databind method returns, the corresponding control will pop up from the stack. If the stack is empty and Eval is called programmatically, getdataitem throws an invalid operation exception. In general, the eval shortcut can only be used in the template. to access data item attributes elsewhere, you must use databinder. eval and explicitly specify the data item object.

Bind Method

The bind method can also be used where the eval method is used. The syntax of the two methods is similar:

<asp:TextBox Runat="server" ID="TheNotes" Text='<%# Bind("notes") %>' />

The biggest difference is that bind can be executed in two directions-read and write. For example, when setting the text attribute, the behavior of the BIND method is the same as that of the eval method. When text is read, bind stores the value in the set. The data binding control in ASP. NET can automatically obtain these values, fill them with the list of parameters for inserting or editing commands, and execute these commands on the data source. The name passed to the BIND parameter must match the name of the parameter in the command. For example, the preceding text box provides a value for the @ notes parameter.

User-Defined dynamic expressions

Data Binding expressions are not real dynamic expressions. They are only calculated in the context of data binding calls.

The dynamic expression is similar to the data binding syntax. It uses the $ prefix. Dynamic expressions are calculated during page compilation. The content of the expressions is extracted, converted to code, and injected into the code generated for the page. There are several existing expression generators:

You can also bind a property of a control to the value of an expression in the following mode:

<% $ Expression %>

The exact syntax depends on the definition of the generator associated with each expression. Note that text expressions are not allowed in the page body. In other words, we can only apply an expression to the properties of the control, rather than using it as follows:

We should encapsulate the expression in the server control. The simplest is to use the literal control. The Code is as follows:

Obviously, app_globalresource must contain the appwelcome string resource, and appversionnumber must be set in the web. config file.

The connectionstrings expression is very useful for data source controls. It avoids hard encoding of connection strings in the aspx file.

Developers can define other expressions by writing classes derived from expressionbuilder. To make it recognizable and correctly processed, you must register a custom expression generator in the web. config file.

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.