C # 4.0 Dynamic Object with ASP.NET DataBinding

I am trying to display in ASP.NET GridView a property of a linked object dynamically created using a dynamic object. In my example, DynamicProperties.FullName is dynamic.

My client code:

<asp:ObjectDataSource runat="server" ID="CustomerDataSource" DataObjectTypeName="Customer" TypeName="CustomerCollection" SelectMethod="LoadAll" /> <asp:GridView ID="CustomerGridView" runat="server" AutoGenerateColumns="False" DataSourceID="CustomerDataSource" EnableViewState="False"> <Columns> <asp:BoundField DataField="FirstName" /> <asp:BoundField DataField="LastName" /> <asp:TemplateField> <ItemTemplate> <asp:Label runat="server" Text='<%#Eval("DynamicProperties.FullName")%>' /> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> 

My BLL code (I simplified it for clarity and did not include the CustomerCollection declaration that I use in ASP.NET bindings):

 public partial class Customer { public string FirstName { get; set; } public string LastName { get; set; } private dynamic _dynamicProperties; public dynamic DynamicProperties { get { if (_dynamicProperties == null) { _dynamicProperties = new ExpandoObject(); _dynamicProperties.FullName = FirstName + " " + LastName; } return _dynamicProperties; } } } 

When I run the application, I received the following HttpException error: DataBinding: "System.Dynamic.ExpandoObject" does not contain a property named "FullName".

I am sure that I am doing something wrong, but I can not find what. When I add a property named FullName to my Customer object and let getter return DynamicProperties.FullName, it works like a charm (my ASP.NET Eval refers to FullName in this case, not DynamicProperties.FullName).

Idea? Thanks, Omid.

+4
source share
1 answer

Eval takes object as a type, while you provide dynamic . Thus, the cast will help and use a separate property for Eval :

 <%# (Container.DataItem as dynamic).FullName%> 

Or short: if the object is provided dynamically, it must be treated like any other type, since it is different from the object.

+4
source

Source: https://habr.com/ru/post/1394626/


All Articles