begin process at 2008 05 16 04:40:37
1 173 215 membres
57 nouveaux aujourd'hui
13 970 membres club

Vous ne trouvez pas de réponse à votre problème ? Alors posez la question dans le forum.
Souvenez-vous qu'il n'y a jamais de question bête, mais rester dans l'ignorance parce que l'on n'ose pas poser une question, ça c'est une erreur !

POSTBACKCONTROL - COMMUNICATION CLIENT/SERVEUR AVEC LES UPDATEPANELS


Information sur la source

Catégorie :ASP.Net Source .NET ( DotNet ) Classé sous : updatepanel, ajax, json, communication, WebControl Niveau : Initié Date de création : 10/10/2007 Date de mise à jour : 21/03/2008 12:54:30 Vu : 5 786

Note :
9 / 10 - par 1 personne
9,00 / 10

  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10

Commentaire sur cette source (3)
Ajouter un commentaire et/ou une note


Description

Ce contrôle permet de communiquer entre JavaScript et ASP.net par l'intermédiaire d'un UpdatePanel.
Il donne seulement la possibilité à JavaScript de faire un postback sans devoir passer par un composant autre tel un LinkButton.


Voici un exemple d'utilisation :
   <asp:UpdatePanel runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <asp:Literal runat="server" ID="litTest" />
            <cs:PostBackControl runat="server" ID="pbcTest" OnCallBack="pbcTest_CallBack"/>
        </ContentTemplate>
    </asp:UpdatePanel>
    <button id="btn1">Je suis un button</button>
    <cs:Script runat="server">
        window.pageLoad = function(){
            $addHandler($get('btn1'), 'click', function(e){
                <%=pbcTest.GetCallBackFunction("'premier test'") %>
                e.preventDefault();
            });
        }
    </cs:Script>

On peut également passer des paramètres en client et serveur en JSON grâce au sérialiseur JSON intégré à ASP.net Ajax :

   <asp:UpdatePanel runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <asp:Literal runat="server" ID="litTest" />
            <cs:PostBackControl runat="server" ID="pbcTest" OnCallBack="pbcTest_CallBack" DeserializeCallBackArgument="true"/>
        </ContentTemplate>
    </asp:UpdatePanel>
    <button id="btn1">Je suis un button</button>
    <cs:Script runat="server">
        window.pageLoad = function(){
            $addHandler($get('btn1'), 'click', function(e){
                var o = {prop1:'value1',prop2:'value2'};
                var s = Sys.Serialization.JavaScriptSerializer.serialize(o);
                <%=pbcTest.GetCallBackFunction("s")%>
                e.preventDefault();
            });
        }
    </cs:Script>

    protected void pbcTest_CallBack(object sender, CallBackEventArgs e)
    {
        litTest.Text = ((Dictionary<String, Object>)e.CallBackArgument)["prop1"].ToString();
    }

Source

  • using System;
  • using System.Collections.Generic;
  • using System.Text;
  • using System.Web.UI;
  • using System.ComponentModel;
  • using System.Web.Script.Serialization;
  • using System.Web.UI.WebControls;
  • namespace CS.Web.UI.WebControls
  • {
  • public class CallBackEventArgs : EventArgs
  • {
  • internal CallBackEventArgs(Object callBackArgument)
  • {
  • this._callBackArgument = callBackArgument;
  • }
  • private Object _callBackArgument;
  • public Object CallBackArgument
  • {
  • get { return _callBackArgument; }
  • set { _callBackArgument = value; }
  • }
  • }
  • [NonVisualControl()]
  • [DefaultEvent("CallBack")]
  • [ToolboxData(@"<{0}:PostBackControl runat=""server"" />")]
  • public class PostBackControl : WebControl, IPostBackEventHandler
  • {
  • private Boolean _deserializeCallBackArgument = true;
  • /// <summary>
  • /// Gets or sets a value indicating whether the argument has to be JSON deserialized.
  • /// </summary>
  • /// <value>
  • /// <c>true</c> if the argument must be JSON Deserialized otherwise, <c>false</c>.
  • /// </value>
  • /// <author>Cyril</author>
  • [DefaultValue(true)]
  • public Boolean DeserializeCallBackArgument
  • {
  • get { return _deserializeCallBackArgument; }
  • set { _deserializeCallBackArgument = value; }
  • }
  • /// <summary>
  • /// Occurs when the JavaScript call it.
  • /// </summary>
  • public event EventHandler<CallBackEventArgs> CallBack;
  • /// <summary>
  • /// When implemented by a class, enables a server control to process an event raised when a form is posted to the server.
  • /// </summary>
  • /// <param name="eventArgument">A <see cref="T:System.String"></see> that represents an optional event argument to be passed to the event handler.</param>
  • public void RaisePostBackEvent(string eventArgument)
  • {
  • if (CallBack != null)
  • {
  • if (_deserializeCallBackArgument)
  • {
  • CallBack.Invoke(this, new CallBackEventArgs(new JavaScriptSerializer().DeserializeObject(eventArgument)));
  • }
  • else
  • {
  • CallBack.Invoke(this, new CallBackEventArgs(eventArgument));
  • }
  • }
  • }
  • /// <summary>
  • /// Gets the call back function.
  • /// </summary>
  • /// <param name="arguments">The arguments, will be evaluated by javascript.</param>
  • public String GetCallBackFunction(String arguments)
  • {
  • if (String.IsNullOrEmpty(arguments)) {
  • arguments = "''";
  • }
  • this.EnsureID();
  • // Page.ClientScript.GetPostBackEventReference ne convient pas car elle convertis l'argument en String JavaScript
  • // on ne peut donc pas intéragir directement avec JavaScript.
  • return String.Format("__doPostBack('{0}',{1});", this.UniqueID, arguments);
  • }
  • }
  • }
using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI;
using System.ComponentModel;
using System.Web.Script.Serialization;
using System.Web.UI.WebControls;

namespace CS.Web.UI.WebControls
{
    public class CallBackEventArgs : EventArgs
    {
        internal CallBackEventArgs(Object callBackArgument)
        {
            this._callBackArgument = callBackArgument;
        }

        private Object _callBackArgument;

        public Object CallBackArgument
        {
            get { return _callBackArgument; }
            set { _callBackArgument = value; }
        }

    }

    [NonVisualControl()]
    [DefaultEvent("CallBack")]
    [ToolboxData(@"<{0}:PostBackControl runat=""server"" />")]
    public class PostBackControl : WebControl, IPostBackEventHandler
    {

        private Boolean _deserializeCallBackArgument = true;

        /// <summary>
        /// Gets or sets a value indicating whether the argument has to be JSON deserialized.
        /// </summary>
        /// <value>
        /// 	<c>true</c> if the argument must be JSON Deserialized otherwise, <c>false</c>.
        /// </value>
        /// <author>Cyril</author>
        [DefaultValue(true)]
        public Boolean DeserializeCallBackArgument
        {
            get { return _deserializeCallBackArgument; }
            set { _deserializeCallBackArgument = value; }
        }

        /// <summary>
        /// Occurs when the JavaScript call it.
        /// </summary>
        public event EventHandler<CallBackEventArgs> CallBack;

        /// <summary>
        /// When implemented by a class, enables a server control to process an event raised when a form is posted to the server.
        /// </summary>
        /// <param name="eventArgument">A <see cref="T:System.String"></see> that represents an optional event argument to be passed to the event handler.</param>
        public void RaisePostBackEvent(string eventArgument)
        {
            if (CallBack != null)
            {
                if (_deserializeCallBackArgument)
                {
                    CallBack.Invoke(this, new CallBackEventArgs(new JavaScriptSerializer().DeserializeObject(eventArgument)));
                }
                else
                {
                    CallBack.Invoke(this, new CallBackEventArgs(eventArgument));
                }
            }
        }

        /// <summary>
        /// Gets the call back function.
        /// </summary>
        /// <param name="arguments">The arguments, will be evaluated by javascript.</param>
        public String GetCallBackFunction(String arguments)
        {
            if (String.IsNullOrEmpty(arguments)) { 
                arguments = "''"; 
            }
            this.EnsureID();
            // Page.ClientScript.GetPostBackEventReference ne convient pas car elle convertis l'argument en String JavaScript
            // on ne peut donc pas intéragir directement avec JavaScript.
            return String.Format("__doPostBack('{0}',{1});", this.UniqueID, arguments);
        }
    }
}
09 décembre 2007 22:52:01 :
Pris en compte du Bubbling pour la remonté des events.
21 mars 2008 12:54:30 :
Rajout de la classe CallBackEventArgs
  • signaler à un administrateur
    Commentaire de tleroy le 24/10/2007 14:32:01 9/10

    Salut Cyril,

    C'est possible d'avoir cette source en version VB ?

  • signaler à un administrateur
    Commentaire de Leyendrim le 28/02/2008 10:44:42

    Salut,

    Je n'arrive pas à utiliser ce composant, parceque le CallBackEventArgs est introuvable.
    Utlise tu une biblithèque spécial ?

    Merci

  • signaler à un administrateur
    Commentaire de jesusonline le 21/03/2008 12:55:11 administrateur CS

    Je viens de mettre à jour ce code avec la classe CallBackEventArgs

Ajouter un commentaire

Appels d'offres

Pub



Snippets en rapport

CalendriCode

Mai 2008
LMMJVSD
   1234
567891011
12131415161718
19202122232425
262728293031 

VS Express FR Gratuit !

VS Express en français et 100% gratuit !

Téléchargements

Logiciels à télécharger sur le même thème :

Boutique

Boutique de goodies CodeS-SourceS