Comment acceder aux propriétés d'une page a partir d'un ObjectDataSource ou SqlDataSource ?

 

Il n'existe pas de moyen standard a ma connaissance permetant d'accèder aux propritétés de la page en cours a partir d'un ObjectDataSource ou SqlDataSource et autres, pour remedier a ce petit manque dans Asp.Net 2.0 j'ai créé le code suivant :

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

namespace App_Code
{
    public class PageParameter : Parameter
    {
        public PageParameter() { }
        protected PageParameter(PageParameter original)
            : base(original)
        {
            this.PropertyName = original.PropertyName;
        }

        public PageParameter(string name, string propertyName)
            : base(name)
        {
            this.PropertyName = propertyName;
        }
        public PageParameter(string name, TypeCode type, string propertyName)
            : base(name, type)
        {
            this.PropertyName = propertyName;
        }

        public string PropertyName
        {
            get
            {
                object propertyName = base.ViewState["PropertyName"];
                if (propertyName == null)
                {
                    return string.Empty;
                }
                return (string)propertyName;
            }
            set
            {
                if (this.PropertyName != value)
                {
                    base.ViewState["PropertyName"] = value;
                    base.OnParameterChanged();
                }
            }
        }

        protected override Parameter Clone()
        {
            return new PageParameter(this);
        }
        protected override object Evaluate(System.Web.HttpContext context, System.Web.UI.Control control)
        {
            Page page = (Page)context.Handler;
            System.Reflection.PropertyInfo pi = page.GetType().GetProperty(this.PropertyName);
            if (pi != null)
            {
                return pi.GetValue(page, null);
            }
            return null;
        }
    }
}

pour son utilisation c'est très simple, il suffit de declarer son prefix dans web.config par exemple :

<configuration>

<pages>

<controls>

<add tagPrefix="code" namespace="App_Code"/>

</controls>

</page>

</configuration>

 

et dans la page :

 

    <asp:ObjectDataSource ID="MyObjectDataSource" runat="server" TypeName="MyTypeName" SelectMethod="MySelectMethod">
<SelectParameters>
<code:PageParameter name="TheTitle" propertyName="Title" />
</SelectParameters>
</asp:ObjectDataSource>

 


 


Aucun commentaire: