Shantanu Gupta
Shantanu Gupta

Reputation: 21188

How to bind Complex Entity type to Gridview using ObjectDataSource

I have an entity

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

Now I binds Collection to GridView using ObjectDataSource Control. Under the TemplateField for Dept of Person class looks like

<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>

Now my Grid gets binded using

            <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>

Now when I tries to update this Person entity, it throws error because dropdown displays Value field and text field and Person entity needs a Dept Entity which is actually binded to dropdownlist

Upvotes: 2

Views: 1028

Answers (1)

onof
onof

Reputation: 17367

You shouldn't use complex entities directly in the presentation layer aspx. Because if you domain model change, for example adding some field, you would update every aspx of your application. You should provide a "view model" like this:

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

  public int DeptId{get;set;}
  public string DeptName {get { ... }}
}

It shouldn't be a DTO: you don't need to transfer data to be serialized between hosts, but a model for the view.

A thin layer can convert model entities to view models. It could be a DataObject well supported by ObjectDataSource.

Upvotes: 3

Related Questions