Understanding ASP.NET Eval() and Bind()

前端 未结 2 1855
栀梦
栀梦 2020-11-30 19:42

Can anyone show me some absolutely minimal ASP.NET code to understand Eval() and Bind()?

It is best if you provide me with two separate cod

2条回答
  •  无人及你
    2020-11-30 20:02

    The question was answered perfectly by Darin Dimitrov, but since ASP.NET 4.5, there is now a better way to set up these bindings to replace* Eval() and Bind(), taking advantage of the strongly-typed bindings.

    *Note: this will only work if you're not using a SqlDataSource or an anonymous object. It requires a Strongly-typed object (from an EF model or any other class).

    This code snippet shows how Eval and Bind would be used for a ListView control (InsertItem needs Bind, as explained by Darin Dimitrov above, and ItemTemplate is read-only (hence they're labels), so just needs an Eval):

    
        
            
  • Title:
    Description:
  • Title:
    Description:
  • From ASP.NET 4.5+, data-bound controls have been extended with a new property ItemType, which points to the type of object you're assigning to its data source.

    
    

    Picture is the strongly type object (from EF model). We then replace:

    Bind(property) -> BindItem.property
    Eval(property) -> Item.property
    

    So this:

    <%# Bind("Title") %>      
    <%# Bind("Description") %>         
    <%#  Eval("Title") %> 
    <%# Eval("Description") %>
    

    Would become this:

    <%# BindItem.Title %>         
    <%# BindItem.Description %>
    <%# Item.Title %>
    <%# Item.Description %>
    

    Advantages over Eval & Bind:

    • IntelliSense can find the correct property of the object your're working with
    • If property is renamed/deleted, you will get an error before page is viewed in browser
    • External tools (requires full versions of VS) will correctly rename item in markup when you rename a property on your object

    Source: from this excellent book

提交回复
热议问题