ASP.NET Dynamic Data, Changing the Many-To-Many fieldtemplate to not display links
By default, the Entity Data Model version of Dynamic Data allows you to use a Many-To-Many fieldtemplate user control, which on display shows you a nice list of links for each related entity. However, in some instances you might not want to show links. Perhaps you want to show plain text, or maybe a custom control?
Diving into the code for the Many-To-Many field template, its not clear exactly how the binding is happening. Here is the ASPX file for the Many To Many control, before editing:
<asp:Repeater ID="Repeater1" runat="server">
<ItemTemplate><asp:DynamicHyperLink runat="server"></asp:DynamicHyperLink></ItemTemplate></asp:Repeater>
Not very helpful, right? The normal controls have FieldValueString or some other property from the control available to them to bind. Here, we are in a repeater so one property won't do, we need to peer into the collection or item from the collection at binding time.
The other problem is we can't just expect to know the property name. The property name(s) may be different depending on which Many-To-Many relationship we are dealing with. So we need to know a little about how Dynamic Data works to pull this off.
The first thing we can do is replace our Dynamic Hyperlink (which seems to be smart enough at bind-time to pick up the proper fields) with a Literal or some other control, like so:
<asp:Literal runat="server" Text="<%# GetDisplayString(Container.DataItem) %>" />
cool? Now we have a literal instead of a hyperlink, and we are making a call to a function that we need to define. That function will take the individual item we've bound, and figure out what value to display. Now lets look at the function we need to make in the code behind: protected string GetDisplayString(object value){ MetaTable actualTable = MetaTable.GetTable(value.GetType()); return actualTable.GetDisplayString(value); }
This function is doing two things: It is getting the MetaTable of the object we have by inferring it from the Type of object we are binding to. Then, once it knows the MetaTable it can figure out what the Display Name should be for that field. The Display Name is taken either from the 'TableName' Data Annotation , or if one does not exist, it grabs the first string it can find from the table.
Voila! No Links anymore. That's all you need, and now you might know a little about how Dynamic Data works under the hood.