Postbackcontrol - communication client/serveur avec les updatepanels

Contenu du snippet

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 / Exemple :


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);
        }
    }
}

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.