程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> .NET實例教程 >> UpdatePanel和自定義控件中的客戶端腳本

UpdatePanel和自定義控件中的客戶端腳本

編輯:.NET實例教程

Over the last few weeks since MS Ajax Beta rolled around I’ve been getting a number of reports of the wwHoverPanel control running into some problems when running in combination with MS Ajax. The controls themselves don’t interfere with MS AJAX directly, but if you’re sticking the controls inside of an AJax UpdatePanel() there’s a problem as the script code that the controls spit out don’t get properly generated into the callback generated updates. With the script code missing the controls still work but exhibit some unexpected behaviors. For example a hover panel placed into an update panel will lose it’s positioning in many cases and instead of popping up at the current mouse cursor position will pop up at the border of the container control it lives in.

 

The problem is that Microosft decided in MS AJAX Beta to go with a completely separate script generation engine which is driven through the ScriptManager control. The MS AJax ScriptManager mimics many of the ClIEntScript object’s methods, but provides them as static methods (thankfully! without that we’d be really screwed).

 

So methods like RegisterClientScriptBlock, ResgisterClientScriptResources – anything that deals with getting script code into the page have related static methods in ScriptManager. The ScriptManager methods pass in the Control as an additional first parameter but otherwise mimic the existing ClIEntScriptManager.

 

This new behavior puts existing controls into a bind though – if code uses ClIEntScriptManager then UpdatePanels will not be able to see the script code (if it needs updating in a callback). But at the same time the control developer can’t make the assumption that the MS AJax ScriptManager actually exists.

 

The end result of all of this is that it’s not exactly straight forward to deal with this mismatch and what needs to happen is that a wrapper object needs to be created that can decide which control to use. The wrapper needs to deal with deciding whether MS AJax is available in the application and if it is, using Reflection to Access the ScriptManager to write out any script code.

 

I can’t take credit for this though: Eilon Lipton posted about this issue a while back and his code really was what I needed to get this off the ground, I just wrapped the thing up into a ClientScriptProxy object that I used on a handful of controls. I basically added a handful of the ClIEntScript methods that I use in my applications. Here’s the class:

 

[*** code updated: 12/12/2006 from comments *** ]

 

/// <summary>

/// This is a proxy object for the Page.ClIEntScript and MS AJax ScriptManager

/// object that can Operate when MS Ajax is not present. Because MS AJax

/// may not be available Accessing the methods directly is not possible

/// and we are required to indirectly reference clIEnt script methods through

/// this class.

///

/// This class should be invoked at the Control's start up and be used

/// to replace all calls Page.ClIEntScript. Scriptmanager calls are made

/// through Reflection

/// </summary>

public class ClIEntScriptProxy

{

    private static Type scriptManagerType = null;

 

    // *** Register proxIEd methods of ScriptManager

    private static MethodInfo RegisterClIEntScriptBlockMethod;

    private static MethodInfo RegisterStartupScriptMethod;

    private static MethodInfo RegisterClIEntScriptIncludeMethod;

    private static MethodInfo RegisterClIEntScriptResourceMethod;

    //private static MethodInfo RegisterPostBackControlMethod;

    //private static MethodInfo GetWebResourceUrlMethod;

   

    ClientScriptManager clIEntScript;

 

    /// <summary>

    /// Determines if MsAJax is available in this Web application

    /// </summary>

    public bool IsMsAJax

    {

        get

        {

            if (scriptManagerType == null)

               CheckForMsAJax();

 

            return _IsMsAJax;

        }

    }

    private static bool _IsMsAJax = false;

 

   

    public bool IsMsAJaxOnPage

    {

        get

        {

            return _IsMsAJaxOnPage;

        }

    }

    private bool _IsMsAJaxOnPage = false;

 

 

    /// <summary>

    /// Current instance of this class which should always be used to

    /// Access this object. There are no public constructors to

    /// ensure the reference is used as a Singleton.

    /// </summary>

    public static ClIEntScriptProxy Current

    {

        get

    

  {

                return

                ( HttpContext.Current.Items["__ClIEntScriptProxy"] ??

                (HttpContext.Current.Items["__ClIEntScriptProxy"] =

                    new ClIEntScriptProxy(HttpContext.Current.Handler as Page)))

                as ClIEntScriptProxy;

        }

    }

 

 

    /// <summary>

    /// Base constructor. Pass in the page name so we can pick up

    /// the stock the

    /// </summary>

    /// <param name="CurrentPage"></param>

    protected ClIEntScriptProxy(Page CurrentPage)

    {

        this.clientScript = CurrentPage.ClIEntScript;

    }

 

    /// <summary>

    /// Checks to see if MS AJax is registered with the current

    /// Web application.

    ///

    /// Note: Method is static so it can be directly Accessed from

    /// anywhere

    /// </summary>

    /// <returns></returns>

    public static bool CheckForMsAJax()

    {

        scriptManagerType = Type.GetType("Microsoft.Web.UI.ScriptManager, Microsoft.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35", false);

        if (scriptManagerType != null)

        {

            _IsMsAJax = true;

            return true;

        }

 

       _IsMsAJax = false;

       return false;

    }

 

    /// <summary>

    /// Registers a clIEnt script block in the page.

    /// </summary>

    /// <param name="control"></param>

    /// <;param name="type"></param>

    /// <param name="key"></param>

    /// <param name="script"></param>

    /// <param name="addScriptTags"></param>

    public void RegisterClIEntScriptBlock(Control control, Type type, string key, string script, bool addScriptTags)

    {

        if (this.IsMsAJax)

        {

            if (RegisterClIEntScriptBlockMethod == null)

                RegisterClientScriptBlockMethod = scriptManagerType.GetMethod("RegisterClIEntScriptBlock");

 

            RegisterClIEntScriptBlockMethod.Invoke(null, new object[5] { control, type, key, script, addScriptTags });

        }

        else

            this.clientScript.RegisterClIEntScriptBlock(type, key, script, addScriptTags);

    }

 

    /// <summary>

    /// Registers a startup code snippet that gets placed at the bottom of the page

    /// </summary>

    /// <param name="control"></param>

    /// <param name="type"></param>

    /// <param name="key"></param>

    /// <param name="script"></param>

    /// <param name="addStartupTags"></param>

    public void RegisterStartupScript(Control control, Type type, string key, string script, bool addStartupTags)

    {

        if (this.IsMsAJax)

        {

            if (RegisterStartupScriptMethod == null)

                RegisterStartupScriptMethod = scriptManagerType.GetMethod("RegisterStartupScript");

 

            RegisterStartupScriptMethod.Invoke(null, new object[5] { control, type, key, script, addStartupTags });

        }

        else

            this.clIEntScript.RegisterStartupScript(type, key, script, addStartupTags);

}

 

    /// <summary>

    /// Registers a script include tag into the page for an external script url

    /// </summary>

    /// <param name="control"></param>

    /// <param name="type"></param>

    /// <param name="key"></param>

    /// <param name="url"></param>

    public void RegisterClIEntScriptInclude(Control control, Type type, string key, string url)

    {

        if (this.IsMsAJax)

        {

            if (RegisterClIEntScriptIncludeMethod == null)

                RegisterClientScriptIncludeMethod = scriptManagerType.GetMethod("RegisterClIEntScriptInclude");

 

            RegisterClIEntScriptIncludeMethod.Invoke(null, new object[4] { control,  type, key, url });

        }

        else

            this.clientScript.RegisterClIEntScriptInclude( type, key, url);

    }

 

 

    /// <summary>

    /// Adds a script include tag into the page for WebResource.

    /// </summary>

    /// <param name="control"></param>

    /// <param name="type"></param>

    /// <param name="resourceName"></param>

    public void RegisterClIEntScriptResource(Control control, Type type, string resourceName)

    {

        if (this.IsMsAJax)

        {

            if (RegisterClIEntScriptResourceMethod == null)

                RegisterClientScriptResourceMethod = scriptManagerType.GetMethod("RegisterClIEntScriptResource");

 

            RegisterClIEntScriptResourceMethod.Invoke(null, new object[3] { control, type, resourceName });

        }

        else

            this.clientScript.RegisterClIEntScriptResource(type,resourceName);

    }

 

 

    public string GetWebResourceUrl(Control control, Type type, string resourceName)

    {

        //if (this.IsMsAJax)

        //{

        //    if (GetWebResourceUrlMethod == null)

        //        GetWebResourceUrlMethod = scriptManagerType.GetMethod("GetScriptResourceUrl");

 

        //    return GetWebResourceUrlMethod.Invoke(null, new object[2] { resourceName, control.GetType().Assembly }) as string;

        //}

        //else

        return this.clIEntScript.GetWebResourceUrl(type, resourceName);

    }

 

}

 

The code basically checks to see whether the MS Ajax assembly can be Accessed as a type and if so assumes MS AJax is installed. This is not quite optimal – it’d be better to know whether a ScriptManager is actually being used on the current page, but without scanning through all controls (slow) I can’t see a way of doing that easily.

 

The control caches each of the MethodInfo structures to defer some of the overhead in making the Reflection calls to the ScriptManager methods. I don’t think that Reflection here is going to cause much worry about overhead unless you have a LOT of calls to these methods (I suppose it’s possible if you have lots of resources – think of a control like FreeTextBox for example). Even then the Reflection overhead is probably not worth worrying about.

 

To use this class all calls to ClIEntScript get replaced with call this class instead. So somewhere during initialization of the control I add:

 

protected override void OnInit(EventArgs e)

{

    this.ClientScriptProxy = ClIEntScriptProxy.Current;

    base.OnInit(e);

}

 

And then to use it:

 

this.ClientScriptProxy.RegisterClIEntScriptInclude(this,this.GetType(),

           ControlResources.SCRIPTLIBRARY_SCRIPT_RESOURCE,

           this.ResolveUrl(this.ScriptLocation));

 

Notice the first parameter is the control instance (typically this) just like the ScriptManager call, so there will be a slight change of parameters when changing over from ClIEntScript code.

 

Once I added this code to my controls the problems with Update

Panel went away and it started rendering properly again even with the controls hosted inside of the UpdatePanels.

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved