Monday 26 May 2008

DynamicData Sorting - FilterUserControl and ForeignKey_Edit.ascx user controls

Sorting - FilterUserControl and ForeignKey_Edit.ascx user controls

To sort either the Filter on a list page of the FK drop down lists, you can use DisplayColumnAttribute which can takes upto 3 parameters ColumnName, SortColumn and SortDecending (bool)

Excerpt from the qucik starts page

"When a data field is a foreign key of another table, Dynamic Data displays this column as a link to the other table. Dynamic Data uses the first column of type string as the link text when the relationship between the tables is a one-to-one relationship.

To change the column that is displayed as the value for the foreign key field, you must apply the DisplayColumnAttribute attribute to the partial entity class of the relationship table. You must create a partial class with the name of the table to be able to apply the attribute."

[DisplayColumnAttribute("PostalCode", "PostalCode", false)]
public partial class Customer
{
}
DisplayColumnAttribute.DisplayColumnAttribute(string displayColumn, string sortColumn, bool sortDescending) 

The above image show the fully overloaded constructor for this attribute:

  • string displayColumn - the name of the column to show when using this table in a DropDownList.
  • string sortColumn - the name of the column to sort the DropDownList by
  • bool sortDescending - set to true changes the sort to descending

So by adding this to the Customer table you can change how it is displayed in filter list and FK DropDownLists.

Customer Filter on Orders table Customer FK list on Orders table

Above shows the Customers filter and Customer FK drop down list on the Orders table List and Edit pages.

5 comments:

Anonymous said...

nice!! I will try this and let you know if it worked or not!

Thanks,
Evan

Stephen J. Naughton said...

This is for .Net 3.5 and probably wont work for .Net 4

Steve

Mae said...

Hi, Steve.

I tried to sort the FK value in EF model but failed.
You said above:
"To change the column that is displayed as the value for the foreign key field, you must apply the DisplayColumnAttribute attribute to the partial entity class of the relationship table. You must create a partial class with the name of the table to be able to apply the attribute."

So, I tried this on my EF lookup table partial class:

[DisplayColumn("name_suffix", "display_order",false)]
public partial class lookup_suffix_name
{
}

Any suggestions?

Stephen J. Naughton said...

Hi Mae, did you get any error? if not you will probably find you have a namespace issue.

Steve

Pasha Furman said...

Works for me in .Net 4