谁能给我看一些绝对最小的ASP.NET代码来理解Eval()Bind()

最好能给我提供两个单独的代码片段,或者是网页链接.

推荐答案

对于只读控件,它们是相同的.对于双向数据绑定,使用您想要在其中进行更新、插入等的数据源和声明性数据绑定,您需要使用Bind.

例如,想象一个GridView带有ItemTemplateEditItemTemplate.如果在ItemTemplate中使用BindEval,则没有区别.如果在EditItemTemplate中使用Eval,该值将无法传递到网格绑定到的DataSource中的Update方法.


更新:我想出了这个例子:

<%@ Page Language="C#" %>
<!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">
<head runat="server">
    <title>Data binding demo</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:GridView 
            ID="grdTest" 
            runat="server" 
            AutoGenerateEditButton="true" 
            AutoGenerateColumns="false" 
            DataSourceID="mySource">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <%# Eval("Name") %>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox 
                            ID="edtName" 
                            runat="server" 
                            Text='<%# Bind("Name") %>' 
                        />
                    </EditItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </form>

    <asp:ObjectDataSource 
        ID="mySource" 
        runat="server"
        SelectMethod="Select" 
        UpdateMethod="Update" 
        TypeName="MyCompany.CustomDataSource" />
</body>
</html>

下面是作为对象数据源的自定义类的定义:

public class CustomDataSource
{
    public class Model
    {
        public string Name { get; set; }
    }

    public IEnumerable<Model> Select()
    {
        return new[] 
        {
            new Model { Name = "some value" }
        };
    }

    public void Update(string Name)
    {
        // This method will be called if you used Bind for the TextBox
        // and you will be able to get the new name and update the
        // data source accordingly
    }

    public void Update()
    {
        // This method will be called if you used Eval for the TextBox
        // and you will not be able to get the new name that the user
        // entered
    }
}

Asp.net相关问答推荐

asp.net 单选按钮分组

更改 GridView 中列的标题文本

由于缺少定义,在 .net Core 应用程序上构建失败

如何将 global.asax 文件添加到 ASP.NET MVC4 项目?

HttpContext.Current.Request.IsAuthenticated 和 HttpContext.Current.User.Identity.IsAuthenticated 有什么区别?

ASP.NET Core 中的授权. [Authorize] 属性总是 401 Unauthorized

如何将 Web 应用程序项目转换为类库项目

ASP.NET RadioButton 与名称(组名)混淆

如何在新选项卡中打开 asp:HyperLink.NavigateUrl

asp.net 有控制台日志(log)吗?

您使用哪个 .NET Memcached 客户端,EnyimMemcached 与 BeITMemcached?

asp.net 网站上的第一页加载缓慢

如何获取程序集的最后修改日期?

覆盖静态方法

ASP .NET 单例

ASP.NET 应用程序状态与静态对象

Twitter Bootstrap 和 ASP.NET GridView

配置授权服务器端点

为什么 IFormFile 显示为空,我该如何解决?

Application_End global.asax