Showing posts with label Limit FilterRepeater. Show all posts
Showing posts with label Limit FilterRepeater. Show all posts

Thursday, 22 May 2008

DynamicData - Limit the Filter Fields

Articles in this Series

Limit the Filter Fields

Below is the attribute and helper class.

using System;
using System.Linq;
using System.Web.DynamicData;

/// <summary>
/// attribute to suppress an MetaChildColumn or MetaParetnColumn in the 
/// filter repeater
/// </summary>
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class HideInFilterAttribute : System.Attribute
{
    // this property is required to work with "AllowMultiple = true" ref David Ebbo
    // As implemented, this identifier is merely the Type of the attribute. However, 
    // it is intended that the unique identifier be used to identify two 
    // attributes of the same type.
    public override object TypeId { get { return this; } }

    /// <summary>
    /// Constructor
    /// </summary>
    public HideInFilterAttribute()
    {
    }
}

/// <summary>
/// Permissions Attributes Helper Extension Methods
/// </summary>
public static class HideInFilterAttributesHelper
{
    public static Boolean ContainsHideInFilter(this MetaColumn column)
    {
        // thanks to Marcin Dobosz for this really elegant code
        return column.Attributes.OfType<HideInFilterAttribute>().FirstOrDefault() != null;
    }
}
Listing 1

Sample metadata

[MetadataType(typeof(OrderMetadata))]
public partial class Order
{
}

public class OrderMetadata
{
    // entities
    [HideInFilter]
    public Object Employee { get; set; }
}
Listing 2

And in the code on the page (i.e. List.aspx.cs) an OnItemDataBound="FilterRepeater_ItemDataBound" is added to the FilterRepeater.

<asp:FilterRepeater 
    ID="FilterRepeater" 
    runat="server" 
    onitemdatabound="FilterRepeater_ItemDataBound" >
Listing 3

In the OnItemDataBound method I check for the metadata using the helper method (which make the code more readable) and set the e.Item.Visible = false.

protected void FilterRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    var column = e.Item.DataItem as MetaColumn;
    if (column != null)
    {
        if (column.ContainsHideInFilter())
            e.Item.Visible = false;
    }
}
Listing 4

Now just by adding metadata to any field (MetaForeignKeyColumn or MetaChildrenColumn), then that filter field can be hidden.