如何将使用 Ajax webmethods 的 ASP.NET 页面转换为支持 Ajax 的服务器控件?

发布于 2024-07-09 10:17:24 字数 2870 浏览 10 评论 0原文

我正在阅读的本教程中, Dave Ward 创建一个页面,在标签中显示服务器日期,而无需使用更新面板。

我正在尝试学习如何创建使用ajax进行部分回发的服务器控件,其中从同一控件生成的客户端脚本调用控件内的方法,并且我认为学习如何将此页面转换为服务器控件将有助于我理解服务器控件使用什么而不是 webmethods 将其方法公开给客户端脚本。

我完全按照文章所述创建了页面、代码隐藏和 javascript,并使示例正常工作。

因此,为了开始尝试将其转换为服务器控件,我将页面的 Dave Javascript 移至文件 ~tests/JScript.js 中:

 function UpdateTime() {
   PageMethods.GetCurrentDate(OnSucceeded, OnFailed); 
 }
 
 function OnSucceeded(result, userContext, methodName) {
   $get('Literal1').innerHTML = result; 
 }
 
 function OnFailed(error, userContext, methodName) {
   $get('Literal1').innerHTML = "An error occured.";
 }

并将以下类放入我的 App_Code 中:

namespace foo
{
    /// <summary>
    /// Summary description for ServerControlTest
    /// </summary>
    public class ServerControlTest : CompositeControl, IScriptControl
    {
        ScriptManager sm;
        protected override void OnPreRender(EventArgs e)
        {
            if (!this.DesignMode)
            {
                // Test for ScriptManager and register if it exists
                sm = ScriptManager.GetCurrent(Page);

                if (sm == null)
                    throw new HttpException("A ScriptManager control must exist on the current page.");

                sm.RegisterScriptControl(this);
                sm.EnablePageMethods = true;
            }

            base.OnPreRender(e);
        }

        protected override void OnLoad(EventArgs e)
        {
            Literal lit = new Literal();
            lit.Text = "<span ID=\"Literal1\" runat=\"server\">test</span><input id=\"Button1\" type=\"button\" value=\"button\"  onclick=\"UpdateTime();\" />";

            this.Controls.Add(lit);
        }
        protected override void Render(HtmlTextWriter writer)
        {
            if (!this.DesignMode)
                sm.RegisterScriptDescriptors(this);

            base.Render(writer);
        }

        [WebMethod]
        public static string GetCurrentDate()
        {
            return DateTime.Now.ToString();
        }

        #region IScriptControl Members

        IEnumerable<ScriptDescriptor> IScriptControl.GetScriptDescriptors()
        {
            return null;
        }

        IEnumerable<ScriptReference> IScriptControl.GetScriptReferences()
        {
            ScriptReference reference = new ScriptReference();
            reference.Path = ResolveClientUrl("~/tests/JScript.js");

            return new ScriptReference[] { reference };
        }

        #endregion
    }
}

现在,在我的示例页面中,当我单击按钮,我收到此错误: PageMethods 未定义 [中断此错误] PageMethods.GetCurrentDate(OnSucceeded, OnFailed);

如何从我的控件注册的客户端脚本调用 GetCurrentDate?

In this tutorial I am reading, Dave Ward creates a page that shows the server date in a label without using the update panel.

I am trying to learn how to create servercontrols that use ajax for partial postbacks where methods within the control are called from clientscript generated by the same control, and I think that learning how to convert this page to a server control would be a help me understand what servercontrols use instead of webmethods to expose their methods to clientscript.

I created the page, codebehind, and javascript exactly as the article indicated and got the sample to work.

So, to start trying to convert this to a servercontrol, I moved Dave's Javascript for the page into a file, ~tests/JScript.js:

 function UpdateTime() {
   PageMethods.GetCurrentDate(OnSucceeded, OnFailed); 
 }
 
 function OnSucceeded(result, userContext, methodName) {
   $get('Literal1').innerHTML = result; 
 }
 
 function OnFailed(error, userContext, methodName) {
   $get('Literal1').innerHTML = "An error occured.";
 }

And put the following class in my App_Code:

namespace foo
{
    /// <summary>
    /// Summary description for ServerControlTest
    /// </summary>
    public class ServerControlTest : CompositeControl, IScriptControl
    {
        ScriptManager sm;
        protected override void OnPreRender(EventArgs e)
        {
            if (!this.DesignMode)
            {
                // Test for ScriptManager and register if it exists
                sm = ScriptManager.GetCurrent(Page);

                if (sm == null)
                    throw new HttpException("A ScriptManager control must exist on the current page.");

                sm.RegisterScriptControl(this);
                sm.EnablePageMethods = true;
            }

            base.OnPreRender(e);
        }

        protected override void OnLoad(EventArgs e)
        {
            Literal lit = new Literal();
            lit.Text = "<span ID=\"Literal1\" runat=\"server\">test</span><input id=\"Button1\" type=\"button\" value=\"button\"  onclick=\"UpdateTime();\" />";

            this.Controls.Add(lit);
        }
        protected override void Render(HtmlTextWriter writer)
        {
            if (!this.DesignMode)
                sm.RegisterScriptDescriptors(this);

            base.Render(writer);
        }

        [WebMethod]
        public static string GetCurrentDate()
        {
            return DateTime.Now.ToString();
        }

        #region IScriptControl Members

        IEnumerable<ScriptDescriptor> IScriptControl.GetScriptDescriptors()
        {
            return null;
        }

        IEnumerable<ScriptReference> IScriptControl.GetScriptReferences()
        {
            ScriptReference reference = new ScriptReference();
            reference.Path = ResolveClientUrl("~/tests/JScript.js");

            return new ScriptReference[] { reference };
        }

        #endregion
    }
}

Now, in my sample page, when I click the button, I get this error:
PageMethods is not defined
[Break on this error] PageMethods.GetCurrentDate(OnSucceeded, OnFailed);

How do I call GetCurrentDate from the clientscript that my control registers?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

小草泠泠 2024-07-16 10:17:24

从 v3.5 开始,实际上还没有完全封装的方法来实现针对服务器控件方法的 AJAX 回调。 这是一个非常令人沮丧的限制。

最常见的解决方案是在服务器控件的程序集中创建 HttpHandler,然后要求在 web.config 中注册该处理程序。 例如,看看 ASP.NET AJAX 的 ScriptResource.axd 在 ASP.NET AJAX 1.0 的 web.config 中是如何连接的。

There is actually no fully encapsulated method for implementing AJAX callbacks against methods of a server control yet, as of v3.5. It's a very frustrating limitation.

The most common solution is to create an HttpHandler in your server control's assembly, then require that the handler be registered in the web.config. Look at how ASP.NET AJAX's ScriptResource.axd is wired up in the web.config in ASP.NET AJAX 1.0, for example.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文