ASP.NET Dynamic Data - Display Custom Text in a Foreign Key DropDownList/ComboBox

Some thoughts scribbled down on Tuesday 24 February 2009 at 01:21 PM

I got asked a question recently about ASP.NET Dynamic Data and how to customize the display text of foreign key dropdownlists/comboboxes

The exact question was "I have a foreign key to a list of store locations. Each location has an address but the default drop down only shows the state. How do I get it to show: "State - Region - StoreName"

Here's how you do it:

Create a partial class of your domain object and add a new column

[DisplayColumn("DisplayName", "DisplayName", false)]
public partial class Store
{
    [ScaffoldColumn(true)]
    public string DisplayName
    {
        get
        {
            return string.Format("{0}-{1}-{2}", State, Region, StoreName);
        }
    }
}

The key here is to:

  1. Create a new property with the exact formatting that you want (DisplayName in this example)
  2. Add the ScaffoldColumn attribute to the property and set it to true
  3. Add the DisplayColumn attribute to the class and use DisplayName

Note: if you don't scaffold the column you will get an error like:

System.Web.DynamicData.MetaTable.get_DisplayColumn()
The display column 'DisplayName' specified for the table 'Stores' does not exist.

Comments

Thu 26 Feb 2009 at 5:03 PM

Peter Bennett → www.peterbennett.net

Hi Eric,

Slightly 'off topic' - I was checking out an article of yours about 'Dynamic Data' and then clicked on your 'photos' tab. I was amazed/surprised to see a Pomchi(?) and a shiver ran down my spine when I saw 'coco'. We have recently inherited a Pomchi, called, you guessed it, Coco. We're besotted with him. Pic at www.hollywoodgnats.blogspot.com

Permalink

Fri 27 Feb 2009 at 3:01 AM

Peter Bennett → www.peterbennett.net

Ah in the cold light of day yours looks like a pure-bred Pom, beautiful. Great set of photos, I feel like I know him/her already! Thought I'd imagined 'Coco' until I moused over!

Permalink

Tue 05 May 2009 at 7:02 PM

Armando Paliani

I'm trying the same, but it doesn't work.

[DisplayColumn("FullName", "FullName", false)]

[ScaffoldTable(true)]

[DisplayName("Anagrafica dipendenti")]

public partial class Anagr_Dip

{

[ScaffoldColumn(true)]

public string FullName

{

get

{

return string.Format("{0}-{1}-{2}", Cognome, Nome);

}

}

}

Permalink

Fri 24 Jul 2009 at 6:48 PM

rob

Hi, n00b here, where do i put this code?

Permalink

Thu 07 Jan 2010 at 9:25 AM

Fabio

I couldn't make it work.

The display column 'DisplayDate' specified for the table does not exist.

Using .Net Framework 4.0 BETA

Permalink

Post your comment