Eval and databinder. eval () methods in ASP. NET

Source: Internet
Author: User

1. Bind isBidirectional data binding, Will change only when there is a data source.

2. In net1.x, there are databinder (container. dataitem, "data item ")One-way Data Binding

. Net2.x is simplified to eval ("data item ");

The difference between eval () and databinder () is:

Eval automatically parses fields based on the dataitem attribute of the latest container object (such as datalistitem,

The databinder. Eval parameter must be used to specify the container. For this reason, Eval can only be used in the template of the data-bound control, but cannot be used in the page layer.

Example:

<Asp: datalist id = "datalist1" repeatcolumns = "5" width = "600" runat = "server" performanceid = "objectperformance1">
<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 = "objectperformance1" runat = "server" typename = "datacomponenttableadapters. photostableadapter

"Selectmethod =" getphotosforalbum ">

 

Data Binding can also be part of the theme definition of the control, so that we can freely change the layout and appearance of the templated control by changing the theme. However, the theme template can only use eval (or bind discussed later ). Bind to any userCodeIs forbidden.

1. databinder. Eval usage
// Display two decimal places
<% # Databinder. eval (container. dataitem, "unitprice", "$ {0: F2}") %>

// {0: g} indicates that true or false is displayed.

    1. "12" Height = "12" border = "0" runat = "server"
    2. alternatetext = '<% # databinder. eval (container. dataitem,
    3. "discontinued", "{0: g}") %> '
    4. imageurl = '<% # databinder. eval (container. dataitem,
    5. "discontinued ","~ /Images/{0: g2.16.gif ") %> '/>

<Itemtemplate> <asp: image width = "12" Height = "12" border = "0" runat = "server" alternatetext = '<% # databinder. eval (container. dataitem, "discontinued", "{0: g}") %> 'imageurl = '<% # databinder. eval (container. dataitem, "discontinued ","~ /Images/{0: gw..gif ") %> '/> </itemtemplate>

// Conversion Type
(String) databinder. eval (container, "dataitem. p_ship_time_sbm8"). substring (4, 4)

{0: d} date only displays year, month, and day
{0: yyyy-mm-dd} displays year, month, and day by format
{0: c} currency Style

2. Container. dataitem usage.
This sentence is often used when binding data.Program: <% # Databinder. eval (container. dataitem, "XXXX") %> or <% # databinder. eval (container, "dataitem. XXXX") %>

In addition, Microsoft also said that this method is more efficient than the above two methods.

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

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

Remember to import the namespace system. Data on the front-end page. Otherwise, an error message is generated.

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

This usage is actually the same as <% # (dictionaryentry) container. dataitem). Key %>.

The key is the container. Its namespace is system. componentmodel.

3. Differences between databinder. eval and container. dataitem

What is the difference between databinder. eval (container. dataitem, "name") and container. dataitem ("name?
Databinder is system. A static class in the Web, which provides the eval method to simplify writing data binding expressions. However, it uses reflection and other overhead methods to achieve ease of use, therefore, its performance is not the best. The container is not a static object or method at all. It is ASP. NET page compiler local variables declared in the Data Binding event handler, its type is the data container type of controls that can be bound to data (for example, the data binding container inside the repeater is called repeateritem). In these container classes, dataitem attributes are basically available, therefore, you can write container. dataitem, which returns the data item from the data source you are bound. If your data source is datatable, the Data Type of this data item is actually datarowview.

The data binding expression must be <% # And %> characters. The format is as follows:

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

Or:

<% # Data-binding expression %>

ASP. NET supports hierarchical data binding models. Data Binding expressions use the eval and bind methods to bind data to controls and submit changes to the database.
The eval method is a static one-way (read-only) method. Therefore, the eval function is used for one-way (read-only) binding. This method uses the value of a data field as a parameter and returns it as a string.
The bind method supports the read/write function, so the BIND function is used for Bidirectional (updatable) binding. This method retrieves the value of the data-bound control and submits any changes to the database.
The XPath method supports XML data sources.

Where can data binding expressions appear on the page?

1. You can include the data binding expression on the value side of the attribute name/attribute value pair in the start tag of a server control or common HTML element. For example:

<Asp: textbox id = "textbox1" runat = "server" text = '<% # data binding expression %>'> </ASP: textbox> <br/>
Note: The top-bound expression of the data at this time can be a variable or a C # Or VB with a returned value. can also be the value of a property of a control, or C # Or VB. the value of a field or attribute of the net object. Of course, it can also be a string, such as "hello ".
If the data binding expression is eval ("a field in a table in the Database"), You must place textbox1 in the template of a circular display control, otherwise, you will be prompted that data binding methods such as eval (), XPath (), and bind () can only be used in the context of the data binding control. In fact, you want to place textbox1 in a template of controls such as repeater, datalist, and gridview.

2. The data 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>
In the same way, the "1" clause should be followed.
If the data binding expression is eval ("a field in a table in the Database"), you must <% # eval ("data binding expression 1 ") %> <% # eval ("data binding expression 2") %> is placed in a template for controls such as repeater, datalist, and gridview.

3. You can include data binding expressions in JavaScript code to call C # Or VB. NET methods in JavaScript. For example:

  1. <% @ Page Language = "C #" autoeventwireup = "true" codefile = "default2.aspx. cs" inherits = "default2" %>
  2. <! Doctype HTML public"-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  3. <HTML xmlns =Http://www.w3.org/1999/xhtml>
  4. <Head runat ="Server">
  5. <Title> No title page </title>
  6. <MCE: script language ="JavaScript" type = "text/JavaScript"> <! --
  7. Function getstr ()
  8. {
  9. VaR;
  10. A ='';
  11. A ='<% # Csharptojavascript () %>' // call the C # Method
  12. Alert ();
  13. }
  14. // --> </MCE: SCRIPT>
  15. </Head>
  16. <Body>
  17. <Form ID ="Form1" runat = "server">
  18. <Div>
  19. <Input id ="Button1" type = "button" value = "javascript calls the C # method! "Onclick =" getstr () "/</div>
  20. </Form>
  21. </Body>
  22. </Html>
  23. Using system;
  24. Using system. Data;
  25. Using system. configuration;
  26. Using system. collections;
  27. Using system. Web;
  28. Using system. Web. Security;
  29. Using system. Web. UI;
  30. Using system. Web. UI. webcontrols;
  31. Using system. Web. UI. webcontrols. webparts;
  32. Using system. Web. UI. htmlcontrols;
  33. Public partial class default2: system. Web. UI. Page
  34. {
  35. Protected void page_load (Object sender, eventargs E)
  36. {
  37. Page. databind ();// If a method has a returned value, bind it first to implement JavaScript to call the C # method!
  38. }
  39. Public String csharptojavascript ()
  40. {
  41. Return"Javascript calls the C # method! ";
  42. }
  43. }

<% @ 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"> <HTML xmlns = "http://www.w3.org/1999/xhtml"> <pead runat = "server"> <title> No title page </title> <MCE: script Language = "JavaScript" type = "text/JavaScript"> <! -- Function getstr () {var A; A = ''; A = '<% # csharptojavascript () %>' // call the method alert (A) of C );} // --> </MCE: SCRIPT> </pead> <body> <Form ID = "form1" runat = "server"> <div> <input id = "button1" type = "button" value =" javascript calls the C # method! "Onclick =" getstr () "/</div> </form> </body> </ptml> using 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 s Ender, eventargs e) {page. databind (); // If a method has a returned value, bind it first before javascript can call the C # method!} Public String csharptojavascript () {return "javascript calls the C # method! ";}}

What types of data binding expressions can all be?
1. It can be a variable.
Example: <asp: Label id = "label1" runat = "server" text = "<% # variable name %>"> </ASP: Label>
2. It can be the property value of the server control.
Example: <asp: Label id = "label1" runat = "server" text = "<% # textbox2.text %>"> </ASP: Label>
3. It can be a collection object such as an array.
For example, bind an array to a list control, such as ListBox or repeater, datalist, or gridview, in this case, you only need to set the attribute datasource = '<% # array name %> '.
4. It can be an expression.
For example, if person is an object and name and city are its two attributes, the data binding expression can be written as follows:
<% # (Person. Name + "" + person. City) %>.
5. It can be a method.
For example, <% # GetUserName () %>. GetUserName () is a defined C # method, which generally requires a return value.
6. It can be the fields of the data table obtained by using Eval, datebind. Eval. This is the most common and is no longer an example.

Note: If the data binding expression is used as the attribute value, as long as no double quotation marks appear in the data binding expression, the outermost layer of the <% # data binding expression %> can be either double quotation marks or single quotes. If the data binding expression contains double quotation marks, the outermost layer of the <% # data binding expression %> should preferably use single quotation marks.

What are common database-related data binding expressions?

1, <% # databind. eval (container. dataitem, "field name") %>
<% # Databind. eval (container. dataitem, "field name", "{0: c}") %>
There are two other types that are not commonly used:
<% # Databinder. eval (container, "dataitem. Field name") %>
<% # Databinder. eval (container, "dataitem. Field name", {0: c}) %>
Container. dataitem is equivalent to a row record in a table in the database, and a row can have many columns.
The last parameter is in the same format as string. format. For example, C indicates the currency, P indicates the percent sign, D indicates the short date format, F indicates the floating point reality, F3 indicates the last three decimal places, and so on.

Use the Three-object operator? Example:
<% # Databinder. eval (container. dataitem, "field name"). tostring (). Trim (). length> 16? Databinder. eval (container. dataitem, "field name "). tostring (). trim (). substring (0, 16): databinder. eval (container. dataitem, "field name "). tostring (). trim () %>

2, <% # eval ("field name") %>
<% # Eval ("field name", "{0: c}") %>
. NET 2.0 is a new method. It is equivalent to databind. eval.
The last parameter is in the same format as string. format. For example, C indicates the currency, P indicates the percent sign, D indicates the short date format, F indicates the floating point reality, F3 indicates the three digits after the decimal point, and so on.

Example of using the three-object OPERATOR:
<% # (Eval ("gender"). tostring () = "true "? "Male": "female" %>
Gender field type: yes/no (ACCESS), bit (SQL Server)
Example of using method call:
<% # Getuserphoto (eval ("photopath") %>
Getuserphoto () Definition:

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 of the field. For example, C indicates the currency, P indicates the percent sign, D indicates the short date format, F indicates the floating point reality, F3 indicates the last three decimal places, and so on.

Type conversion example: <% # (INT) (datarowview) container. dataitem) ["field name 1"] * (INT) (datarowview) container. dataitem) ["field name 2"] %> means that two fields are multiplied.

Efficiency of the above three binding methods: the eval method will call the databinder. Eval method during execution, and the databinder. Eval method will use reflection to execute post-bound computing during runtime, which will lead to a significant reduction in performance. Therefore, the performance may be significantly reduced. So the three are <% # (Datarowview) container. dataitem) ["field name"] %> The best performance.

 

 

 

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.