programing

ASP.NET Eval() 및 Bind() 이해

mailnote 2023. 6. 20. 21:46
반응형

ASP.NET Eval() 및 Bind() 이해

누가 나에게 이해할 수 있는 절대 최소 ASP.NET 코드를 보여줄 수 있습니까?Eval()그리고.Bind()?

두 개의 코드 스니펫을 따로 제공하거나 웹 링크일 수도 있습니다.

읽기 전용 컨트롤의 경우 동일합니다.양방향 데이터 바인딩의 경우 선언적 데이터 바인딩으로 업데이트, 삽입 등을 원하는 데이터 소스를 사용하여Bind.

예를 들어 그리드 보기를 사용하여ItemTemplate그리고.EditItemTemplate사용하는 경우Bind또는Eval에서ItemTemplate차이는 없을 것입니다.사용하는 경우Eval에서EditItemTemplate값을 다음으로 전달할 수 없습니다.Update의 방법DataSource그리드가 구속될 수 있습니다.


업데이트: 다음과 같은 예를 제시했습니다.

<%@ 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
    }
}

Darin Dimitrov에 의해 완벽하게 답변되었지만 ASP.NET 4.5 이후로 이러한 바인딩을 대체할 더 나은 방법이 있습니다*.Eval()그리고.Bind()강력한 구속력을 이용해서요

*참고: 이 기능은 사용하지 않는 경우에만 작동합니다.SqlDataSource또는anonymous objectEF 모델 또는 다른 클래스의 강력한 유형의 개체가 필요합니다.

이 코드 조각은 다음과 같은 방법을 보여줍니다.Eval그리고.Bind에 사용될 것입니다.ListView제어(InsertItem필요.Bind위의 다린 디미트로프가 설명한 바와 같이, 그리고.ItemTemplate읽기 전용이므로(라벨인 경우), 필요한 것은 다음과 같습니다.Eval):

<asp:ListView ID="ListView1" runat="server" DataKeyNames="Id" InsertItemPosition="LastItem" SelectMethod="ListView1_GetData" InsertMethod="ListView1_InsertItem" DeleteMethod="ListView1_DeleteItem">
    <InsertItemTemplate>
        <li>
            Title: <asp:TextBox ID="Title" runat="server" Text='<%# Bind("Title") %>'/><br />         
            Description: <asp:TextBox ID="Description" runat="server" TextMode="MultiLine" Text='<%# Bind("Description") %>' /><br />        
            <asp:Button ID="InsertButton" runat="server" Text="Insert" CommandName="Insert" />        
        </li>
    </InsertItemTemplate>
    <ItemTemplate>
        <li>
            Title: <asp:Label ID="Title" runat="server" Text='<%#  Eval("Title") %>' /><br />
            Description: <asp:Label ID="Description" runat="server" Text='<%# Eval("Description") %>' /><br />        
            <asp:Button ID="DeleteButton" runat="server" Text="Delete" CommandName="Delete" CausesValidation="false"/>
        </li>
      </ItemTemplate>

ASP.NET 4.5+부터는 데이터 바인딩 제어가 새 속성으로 확장되었습니다.ItemType데이터 원본에 할당하는 개체의 유형을 나타냅니다.

<asp:ListView ItemType="Picture" ID="ListView1" runat="server" ...>

Picture(EF 모델에서) 강한 유형의 객체입니다.그런 다음 다음을 대체합니다.

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

그래서 이것은:

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

다음과 같이 됩니다.

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

평가 및 바인딩과 비교한 이점:

  • IntelliSense는 작업enter image description here 중인 개체의 올바른 속성을 찾을 수 있습니다.
  • 속성의 이름을 변경/삭제하면 브라우저에서 페이지를 보기 전에 오류가 발생합니다.
  • 개체의 속성 이름을 변경할 때 외부 도구(VS의 전체 버전 필요)가 마크업 중인 항목의 이름을 올바르게 변경합니다.

출처: 이 훌륭한 에서.

언급URL : https://stackoverflow.com/questions/1778221/understanding-asp-net-eval-and-bind

반응형