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 : 10 178

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

  • 1

  • 2

  • 3

  • 4

  • 5

  • 6

  • 7

  • 8

  • 9

  • 10

Commentaire sur cette source (5)
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);
        }
    }
}

Historique

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

Commentaires et avis

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

signaler à un administrateur
Commentaire de jabcoco25 le 10/09/2008 05:14:34

Quelqu'un a une ideé de ou provien ce code "<cs:Script runat="server">..."
J'obtien une erreur lors de la compilation...

merci!

signaler à un administrateur
Commentaire de grapevine le 03/10/2008 17:27:29

Bonjour Jesus !
Je ne sais pas si c'est à cause de IE 7 mais l'appelle de la méthode :
CallBack.Invoke(this,
                        new CallBackEventArgs(
                        new JavaScriptSerializer()
                        .DeserializeObject(eventArgument)
                        )
                      );
(dans le 2eme cas) génère l'erreur suivante :

Invalid JSON primitive: premier.

Aurais-tu une idée d'ou cela peut provenir ?

Ajouter un commentaire

Discussions en rapport avec ce code source dans le forum

[ASP.Net]Ajax Library et UpdatePanel [ par shadow1779 ] Bonjour, j'ai quelques petits problèmes avec l'updatepanel, j'ai essayé sur mon site que je suis en train de créer comme projet ASP.Net Ajax Enabled ajax - updatepanel [ par waterw72 ] Bonjour,J'ai installé asp.net 2.0 ajax pour mettre " à jour " mon site asp.net 1.0Tout fonctionne très bien  ... mais ...UpdatePanel, ContentTemplate Conflits Ajax et WebControl [ par ofonadroite ] Voila mon problème :       L'utilisateur fait une recherche qui, une foit lancee, affiche le résultat dans un gridview lui-même intégré dans un accord Ajax UpdatePanel - récupération des évéenemnts [ par SpanK ] Bonjour,J'utilise une application ASP.NET avec AJAX et notament le UpdatePanel.J'ai un timer qui permet la mise à jour de l'updatepanel toutes les 10 Nouvelle page dans un updatepanel [ par Patate1978 ] Bonjour. Je suis relativement nouveau dans le monde de AJAX. Par contre, j'ai réussi à assimiler le principe de synchronisation partielle. Mon problèm Async postback & UpdatePanel [ par trap13 ] Je suis a la recherche d"une astuce pour synchroniser un morceau de code en javascript. Pour rés Communication entre deux pages [ par hublet ] Bonjour,J'etudie l'ASP. Mon soucis :J'ai une feuille de base (default) que j'ai découpé en région et dans ces régions je placede plus petites page (st AJAX et boutons dynamiques [ par Gastaropod ] Bon, j'ai un soucis assez déroutant.Pour mieux me faire comprendre, je vais expliquer le cheminement que parcoure mon appli afin que ce soit plus expl configurer un site asp.net2.0 pour accepter les composant ajax [ par sammon ] salut;dans mon projet j'ai besoin d'utiliser un composant calendar pour afficher la date (c'est pas le calendar de visual studion 2005) .je voudrais u Ajax error => Sys.WebForm.PageRequestManagerServerException !? [ par jimmy69 ] Bonjour,J'ai une application sous asp net 2.0 avec ajax 1.0 SANS le ajax controle toolkit ok!J'ai une machine de dev win xp sp 2 et IIS 5.1 avec du ht


Nos sponsors

Sondage...

CalendriCode

Juillet 2009
LMMJVSD
  12345
6789101112
13141516171819
20212223242526
2728293031  

Consulter la suite du CalendriCode

Téléchargements

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

Comparez les prix Nouvelle version

Photothèque Nouveau !



Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés
Temps d'éxécution de la page : 0,421 sec

Google Coop CodeS-SourceS Google Coop CodeS-SourceS


Certaines images présentes sur le site (notament certains avatars) sont issues des collections IconShock, donc si vous souhaitez utiliser ces icons vous devez les acheter, ne les copiez pas et ne utilisez pas dans vos sites et applications sans les avoir commandé.