C # Eval () and bind ()

Source: Internet
Author: User

Eval ("") and Bind ("") both a one-way binding, a two-way binding, bind is a two-way binding, but requires data source support
ASP. NET 2.0 improves the data binding operation in the template, simplifying the data binding syntax DataBinder.Eval (Container.DataItem, fieldname) in v1.x to Eval (fieldname). The Eval method, like DataBinder.Eval, can accept an optional format string parameter. The shortened eval syntax differs from DataBinder.Eval in that Eval automatically resolves fields based on the DataItem property of the nearest container object (for example, DataListItem), and DataBinder.Eval needs to use parameters to specify the container. For this reason, eval can only be used in the template of a data-bound control, not the page (page) layer. Of course, DataBinder.Eval is still supported on the ASP. NET 2.0 page, and you can use it in an environment that does not support the simplified Eval syntax.
The following example shows how to use the new simplified eval data binding syntax to bind to the image, label, and Hyperlink controls in the DataList data item template (ItemTemplate).

Codeasp:datalist id= "DataList1" repeatcolumns= "5" width= "All" runat= "server" datasourceid= "ObjectDataSource1" >
<ItemTemplate>
<asp:hyperlink id= "HyperLink1" runat= "server" Navigateurl= ' <%# Eval ("PhotoID", "photoformviewplain.aspx?id={ 0} ")%> ' >
<asp:image id= "Image1" runat= "Server" imageurl= <%# Eval ("FileName", "images/thumbs/{0}")%>/> </asp:HyperLink>
<asp:label id= "CaptionLabel" runat= "server" text= ' <%# Eval ("Caption")%> '/>
</ItemTemplate>
</asp:datalist><br/>
<asp:objectdatasource id= "ObjectDataSource1" runat= "Server" Typename= " Datacomponenttableadapters.photostableadapter "
selectmethod= "Getphotosforalbum" >

Data binding can also be part of the control's theme definition (theme definition) so that we can change the layout and appearance of the templated control at will by changing the theme. However, the theme (subject) template can only use eval (or bind that is discussed later). Binding to arbitrary user code is forbidden.

1.databinder.eval usage
Show two decimal places
<%# DataBinder.Eval (Container.DataItem, "UnitPrice", "${0:f2}")%>

{0:g} represents display True or false

Codeitemtemplate>
<asp:image width= "height=" border= "0" runat= "Server"
Alternatetext= ' <%# DataBinder.Eval (Container.DataItem,

"Discontinued", "{0:g}")%> '
Imageurl= ' <%# DataBinder.Eval (Container.DataItem,

"Discontinued", "~/images/{0:g}.gif")%> '/>
</ItemTemplate>

Conversion type
(string) DataBinder.Eval (Container, "DATAITEM.P_SHIP_TIME_SBM8")). Substring (bis)

{0:D} date only displays month date
{0:YYYY-MM-DD} displays month date by format
{0:C} currency style


2.container.dataitem usage.
This sentence program is often used when binding data: <%# DataBinder.Eval

(Container.DataItem, "xxxx")%> or <%# DataBinder.Eval

(Container, "dataitem.xxxx")%>

There is one more, and Microsoft says the method is more efficient than both.

<%# ((DataRowView) container.dataitem) ["XXXX"]%>

Very useful, so you can do a lot of things on the front page.

And remember to use it. You must import the namespace System.Data on the foreground page, or you will generate an error message.

<%@ Import namespace= "System.Data"%>

This usage is in fact <%# ((DictionaryEntry) Container.DataItem). Key%> is a truth.

The key is container this thing, its name space is System.ComponentModel.


The difference between 3.databinder.eval and Container.DataItem

What is the difference between DataBinder.Eval (Container.DataItem, "name") and Container.DataItem ("name")?
DataBinder is a static class inside the system.web that provides the Eval method for simplifying the writing of data-binding expressions, but it uses a much more expensive method such as reflection to achieve ease of use, so its performance is not the best. And container is not a static object or method at all, it is ASP. NET page compiler is a local variable declared inside a data-bound event handler whose type is the data container type of the control that can be data-bound (for example, the data-binding container inside the repeater is called RepeaterItem), where the DataItem attribute is basic in these container classes. So you can write Container.DataItem, which returns the data item in the data source that you are bound to. If your data source is a DataTable, the type of the data item is actually DataRowView.

Reference: http://www.cnblogs.com/yangjunwl/articles/1120560.html

The data-binding expression must be contained between the <% #和%> characters. The format is as follows:

<tagprefix:tagname property= ' <%# data-binding expression%> ' runat= "Server"/>

Or as follows:

<%# data-binding Expression%>

ASP. NET supports the hierarchical data-binding model, which uses the Eval and bind methods to bind data to the control and submits the changes back to the database.
The Eval method is a static one-way (read-only) method, so the Eval function is used for one-way (read-only) binding, which takes the value of the data field as a parameter and returns it as a string.
The Bind method supports read/write functionality, so the BIND function is used for two-way (updatable) bindings. The method can retrieve the value of a data-bound control and commit any changes back to the database.
The XPath method supports support for data sources of XML types.

Where can a data-binding expression appear on the page?

One, you can include a data-binding expression in a server control or a normal HTML element in the opening tag of a property name/property value pair of value side. For example:

<asp:textbox id= "TextBox1" runat= "server" text= ' <% #数据绑定表达式%> ' ></asp:textbox><br/>
Note: At this point, the top-bound expression of the data can be a variable, a C # or VB.net method with a return value, a value for a property of a control, a C # or a field for a VB.net object, or the value of a property, and so on. Of course, it can also be a string, such as "Hello".
If the data-binding expression at this time is Eval ("a field in a table in the database"), etc., you must put TextBox1 in the template of the control that is displayed in a loop, otherwise you will be prompted: eval (), XPath (), and Bind () This type of data binding method can only be used in the context of a data-bound control. In fact, you want to put TextBox1 in a template for a control like Repeater,datalist,gridview.

Second, the data-bound binding expression is contained anywhere on the page. For example:


<form id= "Form1" runat= "Server" >
<div>
<% #Eval ("data-binding Expression 1")%>
<% #Eval ("data-binding Expression 2")%>
</div>
</form>
Also follow the "one" notice clause.
If the data-binding expression at this time is Eval ("a field in a table in the database"), the <% must be #Eval ("data-binding Expression 1")%> <% #Eval ("data-binding Expression 2")%> placed in a repeater-like, Datalist,gridview in the template for such a control.

Third, you can include data-binding expressions in JavaScript code to implement methods that call C # or vb.net in JavaScript. For example:

deafult2.aspx:@ page language= "C #" autoeventwireup= "true" codefile= "Default2.aspx.cs" inherits= "DEFAULT2"%>
<! DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 transitional//en" "Http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd ">
<title> Untitled Page </title>
<script language = "javascript" type= "Text/javascript" >
function Getstr ()
{
var A;
A = ";
A= ' <% #CSharpToJavascript ()%> '//method for calling C #
alert (a);
}
</script>
<body>
<form id= "Form1" runat= "Server" >
<div>
<input id= "Button1" type= "button" value= "JavaScript calls C # Method!" onclick= "Getstr ()"/</div>
</form>
</body>

default2.cs: system;
using system.data;
using system.configuration;
using system.collections;
using system.web;
using system.web.security;
using system.web.ui;
using system.web.ui.webcontrols;
using system.web.ui.webcontrols.webparts;
using system.web.ui.htmlcontrols;

Public partial class default2 : system.web.ui.page
{
     protected void page_load (object sender, eventargs e)
     {
        page.databind ();//method has a return value to bind first, in order to implement JavaScript calling C # method !
    }
    public string csharptojavascript ()
    {
        return  "JavaScript calls C # Method!";
    }
}


What types of data-binding expressions can be?
1, can be a variable
Example: <asp:label id= "Label1" runat= "Server" text= "<% #变量名%>" ></asp:Label>
2, can be a property value for a server control
For example: <asp:label id= "Label1" runat= "Server" text= "<% #TextBox2. Text%>" ></asp:Label>
3, which can be a collection object such as an array
For example, to bind an array to a list control, such as a ListBox, or a control such as a repeater,datalist,gridview, you simply need to datasource= the property to the ' <%# array name%> '.
4, can be an expression
For example, if person is an object, name and city are 2 of its properties, the data-binding expression can write:
<%# (Person.name + "" + person.city)%>.
5, can be a method
For example: <% #GetUserName ()%>. GetUserName () is an already defined C # method that typically requires a return value.
6, can be obtained using eval,datebind.eval data table field, this is the most common, no longer an example.

Note: If the data-binding expression is the value of the property, as long as there are no double quotes in the data-binding expression, <% #数据绑定表达式 the outermost of the%> with double or single quotation marks. If double quotes appear in a data-binding expression, it is best to use single quotes for the outermost layer of the <% #数据绑定表达式%>.

What are the common methods for database-related data-binding expressions?

1,<% #DataBind. Eval (Container.DataItem, "field name")%>
<% #DataBind. Eval (Container.DataItem, "field name", "{0:c}")%>
There are also 2 types of infrequently used:
<%# DataBinder.Eval (Container, "DataItem. Field name")%>
<%# DataBinder.Eval (Container, "DataItem. Field name", {0:c})%>
Container.DataItem corresponds to a row of records in a table in a database, and a row can have many columns.
The last parameter is the same as the String.Format form. For example, c for currency, p for percent, D for short date format, F for floating point, F3 for three decimal points, one analogy.

Using the three-mesh operator?: Example:
<%# DataBinder.Eval (Container.DataItem, "field name"). ToString (). Trim (). Length>16? DataBinder.Eval (Container.DataItem, "field name"). ToString (). Trim (). Substring (0,16):D atabinder.eval (Container.DataItem, "field name"). ToString (). Trim ()%>

2,<% #Eval ("field name")%>
<% #Eval ("Field name", "{0:c}")%>
A new method that appears in. NET 2.0. and Databind.eval () are equivalent.
The last parameter is the same as the String.Format form. For example, c for currency, p for percent, D for short date format, F for floating point, F3 for three decimal places, one analogy.

Examples of using the three-mesh operator:
<%# (Eval ("Gender")). ToString () = = "True"? " Male ":" Female "%>
Gender field type: Yes/No (Access), bit (SQL Server)
Examples of using method calls:
<%# Getuserphoto (Eval ("Photopath"))%>
Definition of Getuserphoto ():


String Getuserphoto (Object Photopath)
{
if (Photopath = = DBNull.Value) <%# ((DataRowView) Container.DataItem) ["Field name"]%>

  {
      return "  
  Else
  {
    return "  }
}
 3, <%# ((DataRowView) Container.DataItem) ["Field name"]%>
      <%# String. Format ("{0:c}", ((DataRowView) Container.DataItem) ["Field name]")%>
           use the String.Format method to set the display style for the field. For example, c for currency, p for percent, D for short date format, F for floating point, F3 for three decimal points, one analogy.
      
       Type Conversion Example: <%# (int) ( DataRowView) Container.DataItem) ["Field name 1"]* (int) ((DataRowView) Container.DataItem) ["Field Name 2"]%>    It means 2 characters multiplies multiply.
    
Efficiency of the above three binding methods: The Eval method executes when the DataBinder.Eval method is called, and the DataBinder.Eval method uses reflection to perform late-bound computations at run time. Can cause a noticeable decrease in performance. This results in a noticeable decrease in performance. So the three <%# ((DataRowView) Container.DataItem) ["Field name"]%> the best performance.

C # Eval () and bind ()

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.