locked
How to set the default selected value for the Filters dropdown boxes? RRS feed

  • Question

  • User1432255915 posted

    Hi,

    I have changed the Filters Boolean.ascx.cs code slightly as per the bold highlighted code below because I wanted the Systems page to display only the System's names that have the Active column in the database set to true. (Active - boolean - True / False in the database).

    This seems to be working but if I have another 3 entities with other boolen columns I will have to investigate all of them with "Ifs"

    Is there a better way of deciding the default selected values for the filters (Dropdowns)?

    Cheers

    CP

    protected void Page_Init(object sender, EventArgs e)
    {
                if (!Column.ColumnType.Equals(typeof(bool)))
                {
                    throw new InvalidOperationException(String.Format("A boolean filter was loaded for column '{0}' but the column has an incompatible type '{1}'.", Column.Name, Column.ColumnType));
                }
    
                if (!Page.IsPostBack)
                {
                    DropDownList1.Items.Add(new ListItem("All", String.Empty));
                    if (!Column.IsRequired)
                    {
                        DropDownList1.Items.Add(new ListItem("[Not Set]", NullValueString));
                    }
                    DropDownList1.Items.Add(new ListItem("True", Boolean.TrueString));
                    DropDownList1.Items.Add(new ListItem("False", Boolean.FalseString));
                    // Set the initial value if there is one
                    string initialValue = DefaultValue;
                    if (!String.IsNullOrEmpty(initialValue))
                    {
                        DropDownList1.SelectedValue = initialValue;
                    }
                    else { if (Column.Table.DisplayName == "Systems" && Column.Name == "Active") DropDownList1.SelectedValue = "True"; }             }
    }

     

    asdfasdf

     

    Wednesday, October 3, 2012 9:17 AM

Answers

  • User-330204900 posted

    Hi Pallone, I generally use a custom boolean filter like yours and then use FilterUIHint to set it and I also pass in a value in the control parameters collection

    [FilterUIHint("DefaultValueBoolean"null"Value""True")]
    

    Then I can test for the value from the control parameters

    var filterUIHint = Column.GetAttribute<FilterUIHintAttribute>();
    if (filterUIHint != null && filterUIHint.ControlParameters.ContainsKey("Value"))
        initialValue = filterUIHint.ControlParameters["Value"].ToString();
    
    if (!String.IsNullOrEmpty(initialValue))
        DropDownList1.SelectedValue = initialValue;

    How does that look.

     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, October 3, 2012 10:07 AM
  • User-330204900 posted

    Sorry the code for the GetAttribute is here

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Web.DynamicData;
    using System.ComponentModel;
    using System.Collections;
    
    namespace NotAClue.ComponentModel.DataAnnotations
    {
        public static class AttributeExtensionMethods
        {
            /// <summary>
            /// Gets the control parameter.
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="dictionary">The dictionary.</param>
            /// <param name="key">The key.</param>
            /// <returns></returns>
            /// <remarks></remarks>
            public static T GetControlParameter<T>(this IDictionary<String,object> dictionary, String key)
            {
                if (dictionary.Keys.Contains(key))
                    return (T)dictionary[key];
    
                return default(T);
            }
    
            /// <summary>
            /// Determines whether the specified descriptor has attribute.
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="descriptor">The descriptor.</param>
            /// <returns>
            /// 	<c>true</c> if the specified descriptor has attribute; otherwise, <c>false</c>.
            /// </returns>
            public static Boolean HasAttribute<T>(this PropertyDescriptor descriptor) where T : Attribute
            {
                Boolean value = false;
                for (int i = 0; i < descriptor.Attributes.Count && !value; i++)
                {
                    value = (descriptor.Attributes[i] is T);
                }
    
                return value;
            }
    
            /// <summary>
            /// Gets the attribute.
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="descriptor">The descriptor.</param>
            /// <returns></returns>
            public static T GetAttribute<T>(this PropertyDescriptor descriptor) where T : Attribute
            {
                return descriptor.Attributes.OfType<T>().FirstOrDefault();
            }
    
            /// <summary>
            /// Gets the attribute or default.
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="attributes">The attributes.</param>
            /// <returns></returns>
            public static T GetAttributeOrDefault<T>(this AttributeCollection attributes) where T : Attribute, new()
            {
                return attributes.OfType<T>().DefaultIfEmpty(new T()).FirstOrDefault();
            }
    
            /// <summary>
            /// Gets the attribute.
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="attributes">The attributes.</param>
            /// <returns></returns>
            public static T GetAttribute<T>(this AttributeCollection attributes) where T : Attribute
            {
                return attributes.OfType<T>().FirstOrDefault();
            }
    
            /// <summary>
            /// Get the attribute or a default instance of the attribute
            /// if the Table attribute do not contain the attribute
            /// </summary>
            /// <typeparam name="T">Attribute type</typeparam>
            /// <param name="table">
            /// Table to search for the attribute on.
            /// </param>
            /// <returns>
            /// The found attribute or a default 
            /// instance of the attribute of type T
            /// </returns>
            public static T GetAttributeOrDefault<T>(this MetaTable table) where T : Attribute, new()
            {
                return table.Attributes.OfType<T>().DefaultIfEmpty(new T()).FirstOrDefault();
            }
    
            /// <summary>
            /// Get the attribute of type T or null if not found
            /// </summary>
            /// <typeparam name="T">
            /// Attribute type
            /// </typeparam>
            /// <param name="table">
            /// Table to search for the attribute on.
            /// </param>
            /// <returns>
            /// Returns the attribute T or null
            /// </returns>
            public static T GetAttribute<T>(this MetaTable table) where T : Attribute
            {
                return table.Attributes.OfType<T>().FirstOrDefault();
            }
    
            /// <summary>
            /// Get the attribute or a default instance of the attribute
            /// if the Column attribute do not contain the attribute
            /// </summary>
            /// <typeparam name="T">
            /// Attribute type
            /// </typeparam>
            /// <param name="table">
            /// Column to search for the attribute on.
            /// </param>
            /// <returns>
            /// The found attribute or a default 
            /// instance of the attribute of type T
            /// </returns>
            public static T GetAttributeOrDefault<T>(this MetaColumn column) where T : Attribute, new()
            {
                return column.Attributes.OfType<T>().DefaultIfEmpty(new T()).FirstOrDefault();
            }
    
            /// <summary>
            /// Get the attribute of type T or null if not found
            /// </summary>
            /// <typeparam name="T">Attribute type</typeparam>
            /// <param name="table">Column to search for the attribute on.</param>
            /// <returns>Returns the attribute T or null</returns>
            public static T GetAttribute<T>(this MetaColumn column) where T : Attribute
            {
                return column.Attributes.OfType<T>().FirstOrDefault();
            }
    
            /// <summary>
            /// Gets the attribute or default.
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="column">The column.</param>
            /// <returns></returns>
            public static T GetAttributeOrDefault<T>(this MetaChildrenColumn column) where T : Attribute, new()
            {
                return column.Attributes.OfType<T>().DefaultIfEmpty(new T()).FirstOrDefault();
            }
    
            /// <summary>
            /// Gets the attribute.
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="column">The column.</param>
            /// <returns></returns>
            public static T GetAttribute<T>(this MetaChildrenColumn column) where T : Attribute
            {
                return column.Attributes.OfType<T>().FirstOrDefault();
            }
        }
    }
    

    the FilterUIHint is build in to ASP.Net 4 onwards.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, October 4, 2012 4:57 AM
  • User-330204900 posted

    Hi Pallone, copy the default Boolean filter and rename the update the Page_Init method like so:

    protected void Page_Init(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (!Column.IsRequired)
                DropDownList1.Items.Add(new ListItem("[Not Set]", NullValueString));
    
            PopulateListControl(DropDownList1);
            // Set the initial value if there is one
            string initialValue = DefaultValue;
    
            var filterUIHint = Column.GetAttribute<FilterUIHintAttribute>(); 
            if (filterUIHint != null && filterUIHint.ControlParameters.ContainsKey("Value")) 
                initialValue = filterUIHint.ControlParameters["Value"].ToString(); 
    
            if (!String.IsNullOrEmpty(initialValue))
                DropDownList1.SelectedValue = initialValue;
        }
    }

    remember to renme the inherits attribute in the control directive in the mark-up

    <%@ Control Language="C#" CodeBehind="DefaultValueBoolean.ascx.cs" Inherits="VanillaDD_EF_Project.DefaultValueBooleanFilter" %>
    

    and the class name in the code behind.

    public partial class DefaultValueBooleanFilter : System.Web.DynamicData.QueryableFilterUserControl
    

    all should be good then :)

    Also you will need the GetAttibute Extension method see my post
     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, October 5, 2012 10:21 AM

All replies

  • User-330204900 posted

    Hi Pallone, I generally use a custom boolean filter like yours and then use FilterUIHint to set it and I also pass in a value in the control parameters collection

    [FilterUIHint("DefaultValueBoolean"null"Value""True")]
    

    Then I can test for the value from the control parameters

    var filterUIHint = Column.GetAttribute<FilterUIHintAttribute>();
    if (filterUIHint != null && filterUIHint.ControlParameters.ContainsKey("Value"))
        initialValue = filterUIHint.ControlParameters["Value"].ToString();
    
    if (!String.IsNullOrEmpty(initialValue))
        DropDownList1.SelectedValue = initialValue;

    How does that look.

     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, October 3, 2012 10:07 AM
  • User1432255915 posted

    Hi Steve,

    This is really great. Could you please provide the code for the attribute as well?

    Cheers

    Claudio

    Wednesday, October 3, 2012 11:56 AM
  • User1432255915 posted

    Hi Steve,

    I have tried your code but got this error here: Column.GetAttribute<FilterUIHintAttribute>();

    Error 3 'System.Web.DynamicData.MetaColumn' does not contain a definition for 'GetAttribute' and no extension method 'GetAttribute' accepting a first argument of type 'System.Web.DynamicData.MetaColumn' could be found (are you missing a using directive or an assembly reference?) C:\Dev\BBLDSAccessManager\BBLDSAccessManager\DynamicData\Filters\Boolean.ascx.cs 45 43 BBLDSAccessManager

    I have tried changing the code to this:

    var filterUIHint = Column.Attributes.OfType<FilterUIHintAttribute>();

    But then it breaks the line below:

    filterUIHint.ControlParameters.ContainsKey("Value"))

    Error 4 'System.Collections.Generic.IEnumerable<System.ComponentModel.DataAnnotations.FilterUIHintAttribute>' does not contain a definition for 'ControlParameters' and no extension method 'ControlParameters' accepting a first argument of type

    I have added this to my partial class

    [FilterUIHint("DefaultValueBoolean", null, "Value", "True")]
    public object Active;

    Please can you shed some light?

    Cheers

    CP

    Wednesday, October 3, 2012 12:22 PM
  • User-330204900 posted

    Sorry the code for the GetAttribute is here

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Web.DynamicData;
    using System.ComponentModel;
    using System.Collections;
    
    namespace NotAClue.ComponentModel.DataAnnotations
    {
        public static class AttributeExtensionMethods
        {
            /// <summary>
            /// Gets the control parameter.
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="dictionary">The dictionary.</param>
            /// <param name="key">The key.</param>
            /// <returns></returns>
            /// <remarks></remarks>
            public static T GetControlParameter<T>(this IDictionary<String,object> dictionary, String key)
            {
                if (dictionary.Keys.Contains(key))
                    return (T)dictionary[key];
    
                return default(T);
            }
    
            /// <summary>
            /// Determines whether the specified descriptor has attribute.
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="descriptor">The descriptor.</param>
            /// <returns>
            /// 	<c>true</c> if the specified descriptor has attribute; otherwise, <c>false</c>.
            /// </returns>
            public static Boolean HasAttribute<T>(this PropertyDescriptor descriptor) where T : Attribute
            {
                Boolean value = false;
                for (int i = 0; i < descriptor.Attributes.Count && !value; i++)
                {
                    value = (descriptor.Attributes[i] is T);
                }
    
                return value;
            }
    
            /// <summary>
            /// Gets the attribute.
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="descriptor">The descriptor.</param>
            /// <returns></returns>
            public static T GetAttribute<T>(this PropertyDescriptor descriptor) where T : Attribute
            {
                return descriptor.Attributes.OfType<T>().FirstOrDefault();
            }
    
            /// <summary>
            /// Gets the attribute or default.
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="attributes">The attributes.</param>
            /// <returns></returns>
            public static T GetAttributeOrDefault<T>(this AttributeCollection attributes) where T : Attribute, new()
            {
                return attributes.OfType<T>().DefaultIfEmpty(new T()).FirstOrDefault();
            }
    
            /// <summary>
            /// Gets the attribute.
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="attributes">The attributes.</param>
            /// <returns></returns>
            public static T GetAttribute<T>(this AttributeCollection attributes) where T : Attribute
            {
                return attributes.OfType<T>().FirstOrDefault();
            }
    
            /// <summary>
            /// Get the attribute or a default instance of the attribute
            /// if the Table attribute do not contain the attribute
            /// </summary>
            /// <typeparam name="T">Attribute type</typeparam>
            /// <param name="table">
            /// Table to search for the attribute on.
            /// </param>
            /// <returns>
            /// The found attribute or a default 
            /// instance of the attribute of type T
            /// </returns>
            public static T GetAttributeOrDefault<T>(this MetaTable table) where T : Attribute, new()
            {
                return table.Attributes.OfType<T>().DefaultIfEmpty(new T()).FirstOrDefault();
            }
    
            /// <summary>
            /// Get the attribute of type T or null if not found
            /// </summary>
            /// <typeparam name="T">
            /// Attribute type
            /// </typeparam>
            /// <param name="table">
            /// Table to search for the attribute on.
            /// </param>
            /// <returns>
            /// Returns the attribute T or null
            /// </returns>
            public static T GetAttribute<T>(this MetaTable table) where T : Attribute
            {
                return table.Attributes.OfType<T>().FirstOrDefault();
            }
    
            /// <summary>
            /// Get the attribute or a default instance of the attribute
            /// if the Column attribute do not contain the attribute
            /// </summary>
            /// <typeparam name="T">
            /// Attribute type
            /// </typeparam>
            /// <param name="table">
            /// Column to search for the attribute on.
            /// </param>
            /// <returns>
            /// The found attribute or a default 
            /// instance of the attribute of type T
            /// </returns>
            public static T GetAttributeOrDefault<T>(this MetaColumn column) where T : Attribute, new()
            {
                return column.Attributes.OfType<T>().DefaultIfEmpty(new T()).FirstOrDefault();
            }
    
            /// <summary>
            /// Get the attribute of type T or null if not found
            /// </summary>
            /// <typeparam name="T">Attribute type</typeparam>
            /// <param name="table">Column to search for the attribute on.</param>
            /// <returns>Returns the attribute T or null</returns>
            public static T GetAttribute<T>(this MetaColumn column) where T : Attribute
            {
                return column.Attributes.OfType<T>().FirstOrDefault();
            }
    
            /// <summary>
            /// Gets the attribute or default.
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="column">The column.</param>
            /// <returns></returns>
            public static T GetAttributeOrDefault<T>(this MetaChildrenColumn column) where T : Attribute, new()
            {
                return column.Attributes.OfType<T>().DefaultIfEmpty(new T()).FirstOrDefault();
            }
    
            /// <summary>
            /// Gets the attribute.
            /// </summary>
            /// <typeparam name="T"></typeparam>
            /// <param name="column">The column.</param>
            /// <returns></returns>
            public static T GetAttribute<T>(this MetaChildrenColumn column) where T : Attribute
            {
                return column.Attributes.OfType<T>().FirstOrDefault();
            }
        }
    }
    

    the FilterUIHint is build in to ASP.Net 4 onwards.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, October 4, 2012 4:57 AM
  • User1432255915 posted

    Hi Steve,

    Many thanks for the code. I have 2 questions regarding the code:

    1 - Do I have to add a new Class to the project and copy and paste the code? if so I will have to use the name of the class to call the methos

    AttributeExtensionMethods.GetAttribute

    However, what do I have to do to use it like an extension method without having to call a method?

     

    2 - As per the FilterUIHint you showed, I think I will have to add a new ".ascx" control and call it "DefaultValueBoolean.ascx".

    IS that right?

    3 - I am not sure what code to put in the new DefaultValueBoolean.ascx. Do I have to just copy the current Boolean.ascx control?

    Would you have an example to show me what goes in the new control?

    Cheers,

    CP

     

     

     

    [FilterUIHint("DefaultValueBoolean",null,"Value","True")]

    Thursday, October 4, 2012 2:35 PM
  • User-330204900 posted

    for

    1. you just add it as a class (I keep all my extension methods in seperate classes grouped together) and for
    2. yes just copy the default and rename.

    if you need an example just e-mail me direct and I will create one for you :)

    Thursday, October 4, 2012 7:13 PM
  • User1432255915 posted

    Hi Steve,

    I would appreciate very much if you could provide an example. I will email you directly using your notaclue email.

    Thanks.

     

    Friday, October 5, 2012 10:07 AM
  • User-330204900 posted

    Hi Pallone, copy the default Boolean filter and rename the update the Page_Init method like so:

    protected void Page_Init(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (!Column.IsRequired)
                DropDownList1.Items.Add(new ListItem("[Not Set]", NullValueString));
    
            PopulateListControl(DropDownList1);
            // Set the initial value if there is one
            string initialValue = DefaultValue;
    
            var filterUIHint = Column.GetAttribute<FilterUIHintAttribute>(); 
            if (filterUIHint != null && filterUIHint.ControlParameters.ContainsKey("Value")) 
                initialValue = filterUIHint.ControlParameters["Value"].ToString(); 
    
            if (!String.IsNullOrEmpty(initialValue))
                DropDownList1.SelectedValue = initialValue;
        }
    }

    remember to renme the inherits attribute in the control directive in the mark-up

    <%@ Control Language="C#" CodeBehind="DefaultValueBoolean.ascx.cs" Inherits="VanillaDD_EF_Project.DefaultValueBooleanFilter" %>
    

    and the class name in the code behind.

    public partial class DefaultValueBooleanFilter : System.Web.DynamicData.QueryableFilterUserControl
    

    all should be good then :)

    Also you will need the GetAttibute Extension method see my post
     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, October 5, 2012 10:21 AM
  • User1432255915 posted

    Hi Steve,

    I am having problems with your DataAnnotation class as follows:

    Error 4 The type or namespace name 'RequiredWhenVisibleAttribute' could not be found (are you missing a using directive or an assembly reference?) C:\Dev\BBLDSAccessManager\BBLDSAccessManager\DAL\DataAnnotations.cs 32 48 BBLDSAccessManager

    and

    Error 5 'AttributeCollection' is an ambiguous reference between 'System.Web.UI.AttributeCollection' and 'System.ComponentModel.AttributeCollection' C:\Dev\BBLDSAccessManager\BBLDSAccessManager\DAL\DataAnnotations.cs 72 55 BBLDSAccessManager

    Please can you let me know what I have to do to fix it?

    Cheers,

    CP

     

     

    Thursday, October 11, 2012 9:39 AM
  • User1432255915 posted

    Steve,

    1 - I am also having problems when I call the GetAttribute() method:

    var filterUIHint = Column.GetAttribute<FilterUIHintAttribute>();

    Error 3 The call is ambiguous between the following methods or properties: 'BBLDSAccessManager.DAL.DynamicDataExtensionMethods.GetAttribute<System.ComponentModel.DataAnnotations.FilterUIHintAttribute>(System.Web.DynamicData.MetaColumn)' and 'BBLDSAccessManager.DAL.AttributeExtensionMethods.GetAttribute<System.ComponentModel.DataAnnotations.FilterUIHintAttribute>(System.Web.DynamicData.MetaColumn)' C:\Dev\BBLDSAccessManager\BBLDSAccessManager\DynamicData\Filters\DefaultValueBoolean.ascx.cs 57 36 BBLDSAccessManager

     

    2 - I think that I am still not sure how to use the public static class AttributeExtensionMethods Data Annotation class extension methods you provided in your post.

    Where do I put the class so that my code in the DefaultValueBooleanFilter.asxc.cs can understand the GetAttribute() method?

    Column.GetAttribute<FilterUIHintAttribute>();

    Cheers,

    CP

     

    Thursday, October 11, 2012 10:28 AM
  • User-330204900 posted

    Hi Pallone, is that in the sample I sent you?

    Friday, October 12, 2012 10:46 AM
  • User1432255915 posted

    Hi Steve,

    Unfortunately, I did not get your sample. Did you forget to attach it to the email?

    Cheers,

    CP

     

    Monday, October 15, 2012 3:56 AM
  • User-330204900 posted

    I'll try again sorry about that. Hi Pallone, I didn't send a sample but did include all the required code in my previous posts, I will do a quick sample and e-mail it now :)

    Monday, October 15, 2012 5:50 AM
  • User-330204900 posted

    Sample sent

    Monday, October 15, 2012 6:16 AM
  • User1432255915 posted

    Thank Steve,

    I will have a look.

    CP

    Monday, October 15, 2012 8:23 AM