【问题标题】:How to bind Complex Entity type to Gridview using ObjectDataSource如何使用 ObjectDataSource 将复杂实体类型绑定到 Gridview
【发布时间】:2011-09-19 20:45:38
【问题描述】:

我有一个实体

class Person
{
public int Age{get;set;}
public string Name{get;set;}
public Department Dept{get;set;}
}

class Department
{
public int DeptId{get;set;}
public string DeptName{get;set}
}

现在我使用 ObjectDataSource 控件将 Collection 绑定到 GridView。 在 Dept of Person 类的 TemplateField 下看起来像

<EditItemTemplate>
      <asp:DropDownList ID="cmbStatus" DataTextField="DeptName" SelectedValue='<%# Bind("Dept.DeptId") %>'
          DataValueField="DeptId" runat="server" CssClass="ddl150px ddlbg" 
          DataSourceID="deptCollection" />
      <asp:ObjectDataSource ID="deptCollection" runat="server" 
                   SelectMethod="GetDeptList" TypeName="LIMS.BusinessObject.Department" >
     </asp:ObjectDataSource>
 </EditItemTemplate>

现在我的 Grid 使用

绑定了
            <asp:ObjectDataSource ID="PersonCollection" runat="server" 
                SelectMethod="GetPersonList" 
                TypeName="LIMS.BusinessObject.Person" 
                DataObjectTypeName="LIMS.DomainModel.Person" 
                DeleteMethod="Delete" InsertMethod="Create" UpdateMethod="Update" 
                ondeleting="PersonCollection_Deleting" 
                onupdating="PersonCollection_Updating">  
            </asp:ObjectDataSource>

现在,当我尝试更新此 Person 实体时,它会抛出错误,因为下拉列表显示 Value 字段和文本字段,并且 Person 实体需要一个实际绑定到下拉列表的 Dept 实体

【问题讨论】:

    标签: c# asp.net


    【解决方案1】:

    您不应该直接在表示层 aspx 中使用复杂的实体。因为如果您更改域模型,例如添加一些字段,您将更新应用程序的每个 aspx。您应该提供这样的“视图模型”:

    class PersonView
    {
      public int Age{get;set;}
      public string Name{get;set;}
    
      public int DeptId{get;set;}
      public string DeptName {get { ... }}
    }
    

    它不应该是 DTO:您不需要在主机之间传输要序列化的数据,而是视图的模型。

    薄层可以将模型实体转换为视图模型。它可能是 ObjectDataSource 很好支持的DataObject

    【讨论】:

      猜你喜欢
      • 2013-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-18
      • 2019-05-12
      • 1970-01-01
      • 2011-02-28
      相关资源
      最近更新 更多