Apparently ASP.NET doesn't allow data-binding to dynamic objects. Major bummer, because I could see a syntax like this being really useful:
public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
...
// No this doesn't exist, I just wish it did!
MyGrid.DataSource = GetAllUsers()
.AsDynamic()
.WithProperty("FullName", user => user.FirstName + " " + user.LastName)
.ToEnumerable(); // returns IEnumerable<dynamic>
MyGrid.DataBind()
...
<asp:BoundField DataField="FirstName" HeaderText="First Name" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" />
<asp:BoundField DataField="FullName" HeaderText="Full Name" />
In this example, AsDynamic()
would return a class that would configure the dynamic objects that would be returned by .ToEnumerable()
later (because you can't implement IEnumerable<dynamic>
) effectively adding properties to the wrapped data object. The requests for FirstName and LastName would be "served" by the real object, and the request for FullName would be routed to a delegate or expression to be evaluated dynamically.
This is a trivial example, because in most cases you could easily add a FullName property to the User object, and you could easily pull this off with a TemplatedField.
But what if the added property was way too difficult to implement in a TemplatedField without several lines of databinding codebehind? And what if you didn't control the source code for the User class? Or what if you can't add the property to User because its calculation is dependent on an assembly which itself depends on User's assembly? (circular reference problem)
For this reason it would be great to have a very easy-to-apply data binding wrapper such as this, where you don't have to generate a brand new class every single time.
So what am I really after?
Are there any frameworks or techniques out there that allow this kind of thing? The exact syntax above isn't really important, just the ability to dynamically add stuff to classes and use those proxies in data-binding, without a bunch of manual plumbing code.