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?