While the markup for the controls remains the same in this example, you will set a property in the code-behind that will flag the label control for Anthem.NET to use for updating instead
Trang 1txtTitle_TextChangedevent and will update Session state with the latest value Now when you move to another page and return, this page will have your changed value instead of saying “Title.” You can now launch the page in your browser to test its behavior
What You Have Learned
MagicAjax is a framework that will make any NET developer feel comfortable The panel, changed-HTML-type architecture makes creating Ajax applications easy because the framework is responsible for creating the wireup between the browser and the server In fact, the only custom JavaScript you wrote in these examples was to update style sheet settings and not to facilitate Ajax scripting MagicAjax also provides hooks for you to call code written in your code-behind that is not a part of the traditional ASP.NET Event Postback pattern
Anthem.NET
URL: http://anthem-dot-net.sourceforge.net Although the Anthem.NET framework features panels and a changed HTML architecture, you also have the option of using custom controls and returning data structures to the client Anthem.NET is architected to use page Registerdirectives instead of forcing you to inherit from a base class, and you are not required to implement preprocessing to harness its power Anthem.NET truly represents the best of both worlds
Setup
Before you begin using Anthem.NET, you must first download the files and then reference them in a web project The following steps help you build a solution that houses all the samples you create for the Anthem.NET
Downloading Files
1. If you haven’t done so yet, download the zip file containing the Anthem.NET DLL from http://beginningajax.com/downloads/chapter9/Chapter9-Framework DLLs.zip
2. Extract the files, and place them in a convenient location
Creating the Solution
1. Open Visual Studio 2005
2. Click File➪New➪Website.
3. Select the ASP.NET Website template.
4. Choose File System under location
5. Set the path to c:\BeginningAJAX\Chapter9\AnthemDemo
6. Choose C# as the language.
7. Click OK.
Trang 2Referencing ComfortASP.NET
1. In the Solution Explorer, right-click on the project name and select Add ASP.NET Folder
2. Choose App_LocalResourcesto create the ASP.NET folder
3. Copy Anthem.dll(from the zip file you extracted) to the App_LocalResourcefolder
4. Create a reference to the Anthem.dll
Copying the Data File
1. Copy the Resources.xmlyou created in the last section into the App_Datafolder in the solution
Using Anthem.NET
Since you have had an opportunity to use panels, the coming examples will focus on using Anthem.NET’s custom controls You will also have an opportunity to work with a data structure returned from the server Working with Anthem.NET’s data structures will seem familiar to you because the process is nearly identical to the way you would do it using the Ajax.NET framework
Example 1: Hello World
Anthem.NET’s introductory example will follow the same pattern as the examples for ComfortASP.NET and MagicAjax
This demonstration will use Anthem.NET controls The Anthem button and label inherit from the stan-dard NET controls and extend them for the framework While the markup for the controls remains the same in this example, you will set a property in the code-behind that will flag the label control for Anthem.NET to use for updating instead of the traditional NET postback mechanism
Figure 9-12 shows an example of how the page will look when you are done
Begin by adding a web form to the solution and naming it HelloWorld.aspx Now add the Anthem register directive to the page just under the <%@ Page %>directive
<%@ Register TagPrefix=”anthem” Namespace=”Anthem” Assembly=”Anthem” %>
Next, update the markup by adding the following code between the <div>tags
<anthem:Button
ID=”Button1”
OnClick=”Button1_Click”
Text=”Test”
runat=”server” />
<anthem:Label
ID=”Label1”
runat=”server” />
Trang 3Finally, update the HelloWorldclass with the following code-behind.
public partial class HelloWorld : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
} protected void Button1_Click(object sender, EventArgs e) {
this.Label1.Text = “Hello World “ + DateTime.Now.ToString();
this.Label1.UpdateAfterCallBack = true;
} } When you click on the Test button, the label will update with the text “Hello World” and the current date and time Click the button multiple times to see that the time will continue to be updated without
a postback to the server
You may now test the behavior by launching the page in the browser
Figure 9-12
Trang 4Example 2: Complex Controls
Just as you observed with ComfortASP.NET, the framework operates well with a single textbox, but how will the system perform with more demanding controls? This example will guide you through adding a GridViewcontrol to the page and will use Anthem.NET to respond to the SelectedIndexChanged method
Figure 9-13 is an example of the way the page will look when you are done
Figure 9-13
Begin by adding a new web form to the solution, naming it ComplexControls.aspx Now add the Anthemregister directive to the page just under the <%@ Page %>directive
<%@ Register TagPrefix=”anthem” Namespace=”Anthem” Assembly=”Anthem” %>
Next, update the markup by adding the following code between the <div>tags:
<anthem:Button
ID=”btnLoadResources”
OnClick=”btnLoadResources_Click”
Text=”Load Resources”
runat=”server” />
Trang 5<anthem:gridview id=”grdResources”
runat=”server”
OnSelectedIndexChanged=”grdResources_SelectedIndexChanged”>
<Columns>
<asp:CommandField ShowSelectButton=”True” />
</Columns>
</anthem:gridview>
<p>Selected index:
<anthem:Label ID=”lblSelectedIndex” runat=”server” /></p>
Finally, switch to the code view, and add the following code to the ComplexControlsclass:
public partial class ComplexControls : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
} protected void btnLoadResources_Click(object sender, EventArgs e) {
DataSet ds;
ds = new DataSet();
ds.ReadXml(Server.MapPath(“~/App_Data/Resources.xml”));
this.grdResources.DataSource = ds;
this.grdResources.DataBind();
this.grdResources.UpdateAfterCallBack = true;
} protected void grdResources_SelectedIndexChanged(object sender, EventArgs e) {
this.lblSelectedIndex.Text = this.grdResources.SelectedIndex.ToString(); this.lblSelectedIndex.UpdateAfterCallBack = true;
} } When you click the Load Resources button, the grid is loaded with data from the XML store When you click on a Select link in the grid, the text of the label is updated with the selected index value
You can now test the behavior by launching the page in the browser
Example 3: Custom Attributes
When Anthem.NET extends web controls, part of the new interface includes some attributes you can define to make working with the controls easier In some frameworks, you must manually script a fea-ture to disable a button when a call to the server is initiated With an Anthem button, you may set an attribute that implements this feature for you automatically You may also find that you want to change the text of a button once the page begins to contact the server Again, Anthem.NET’s button control allows you to declaratively define this behavior
Trang 6Figure 9-14 shows an example of how the page will look after you click the button defined with Anthem.NET’s custom attributes
Figure 9-14
Begin by adding a new web form to the solution naming it CustomAttributes.aspx Now add the Anthem register directive to the page just under the <%@ Page %>directive
<%@ Register TagPrefix=”anthem” Namespace=”Anthem” Assembly=”Anthem” %>
Next, update the markup by adding the following code between the <div>tags:
<anthem:Button
ID=”btnTest”
EnabledDuringCallBack=”false”
TextDuringCallBack=”Working ”
Text=”Test”
runat=”server”
OnClick=”btnTest_Click” />
<anthem:Label
ID=”lblTest”
runat=”server” />
Trang 7Finally, update the CustomAttributesclass with the following code-behind:
public partial class CustomAttributes : System.Web.UI.Page {
protected void btnTest_Click(object sender, EventArgs e) {
System.Threading.Thread.Sleep(5000);
this.lblTest.Text = DateTime.Now.ToString();
this.lblTest.UpdateAfterCallBack = true;
} } When you click the Test button, the server will hesitate for 5 seconds before returning a response to the browser During this delay, you may observe that the button is disabled and the text is changed
to “Working ” When the browser regains control of the operation the button is enabled and the text returns to its original value
Now test the behavior by launching the page in the browser
Example 4: Client Functions
In addition to custom attributes, Anthem.NET exposes client-side events These events give you a high degree of control over your page when contacting the server This example will show you how to implement some custom logic before the framework is contacted, before callback begins, and when the callback is completed
When you are wiring up code-behind events on an ASP.NET page, the OnClickattribute will link the client-side click event to the ASP.NET postback mechanism to contact the code on the server to run the click event method defined in your code-behind Anthem.NET implements an OnClientClick attribute where you may define a function name to run after the button is clicked but before the Anthem.NET framework is invoked The PreCallBackFunctionwill fire as Anthem.NET takes control
of the request but before contacting the server Finally, the PostCallBackFunctionwill define a JavaScript function that is run once a response is recognized by the browser
Notice in the example that each JavaScript function is defined passing an argument of thisto the method Passing the argument will expose a reference to the initiating control, in this case the Test but-ton This approach is valuable as you now have an easy way to access the control that originated the request without having to parse the DOM
Figure 9-15 is an example of the way the page will look when you first click on a button using client functions
Trang 8Figure 9-15
Try It Out Using Client Functions
Begin by adding a new web form to the solution, naming it ClientFunctions.aspx Now add the Anthem register directive to the page just under the <%@ Page %>directive:
<%@ Register TagPrefix=”anthem” Namespace=”Anthem” Assembly=”Anthem” %>
Next, add the following code within the <head>tag:
<script type=”text/javascript”>
function btnTest_PreCallBack()
{
alert(“This happens before contacting the server”);
}
function btnTest_PostCallBack()
{
alert(“This happens after getting a “ +
“response from the server”);
}
function btnTest_Click(control)
{
alert(“This happens right after you click the ‘“ +
Trang 9control.value + “‘ button.”);
}
</script>
Each method will alert the browser of which event is firing The btnTest_Clickfunction will access the originating control’s properties to build its statement
Next, update the markup by adding the following code between the <div>tags:
<anthem:Button ID=”btnTest”
OnClientClick=”btnTest_Click(this)”
PreCallBackFunction=”btnTest_PreCallBack(this)”
PostCallBackFunction=”btnTest_PostCallBack(this)”
Text=”Test”
OnClick=”btnTest_Click”
runat=”server” />
<anthem:Label ID=”lblTest”
runat=”server” />
Finally, update the ClientFunctionsclass with the following code-behind:
public partial class ClientFunctions : System.Web.UI.Page {
protected void btnTest_Click(object sender, EventArgs e) {
this.lblTest.Text = DateTime.Now.ToString();
this.lblTest.UpdateAfterCallBack = true;
} } When you click the button, each event will fire the appropriate JavaScript function
You can now test the behavior by launching the page in the browser
Example 5: Invoke Page Method
This example demonstrates how you can use Anthem.NET to call sever-side code without requiring the use of a panel or custom controls Anthem.NET implements this feature in a similar fashion to the Ajax.NET framework, but instead of creating a proxy object for each page that exposes a method to the client, Anthem.NET has a single function that will take care of communicating with the server Anthem.NET’s function for interfacing with the code-behind is called Anthem_InvokePageMethod This function may take three arguments
❑ The first argument is the name of the method on the server you want the function to execute
❑ The second argument is an array of the server-side method argument values
❑ Lastly, the third argument is for the callback function and is the name of the function that the browser will call when the server has completed its processing The callback function argument
Trang 10Figure 9-16 is an example of the way the page will look when you are done.
Figure 9-16
Begin by adding a new web form to the solution, naming it InvokePageMethod.aspx Now add the fol-lowing code within the <head>tag:
<script type=”text/javascript”>
function Multiply()
{
var int1;
var int2;
int1 = document.getElementById(‘txtInt1’).value;
int2 = document.getElementById(‘txtInt2’).value;
Anthem_InvokePageMethod(‘Multiply’,[int1, int2],Multiply_CallBack);
}
function Multiply_CallBack(result)
{
document.getElementById(‘txtResult’).value = result.value;
}
</script>
Trang 11The block of JavaScript is responsible for gathering the user input and passing it to the Anthem_Invoke PageMethodfunction The first argument in this function is the name of the method on the server that you want to execute In an upcoming code block, you will define a method on the page named Multiply, which is the code this function will execute The next argument is an array of values that represent the sig-nature of the Multiplymethod on the server Multiplyrequires two integers to multiply together and returns the result The final argument is the address of the callback function After Multiply_CallBack runs, the textbox txtResult’s value will contain the product of the two numbers
You will not add the Anthem page directive to the page in this example The technique used here will use Anthem.NET’s functionality to access methods in the code-behind directly from JavaScript This approach does not require that you use Anthem.NET controls.
Next, update the markup by adding the following code between the <div>tags:
<input type=”text”
id=”txtInt1” />
<span>X</span>
<input type=”text”
id=”txtInt2” />
<input type=”button”
id=”btnMultiply”
value=”Multiply”
onclick=”Multiply();” />
<input type=”text”
id=”txtResult” />
The HTML you see here is a bit different from the type of markup you have defined in the previous examples In this case, you are not using a panel, nor are you declaring your controls as custom controls This approach uses JavaScript to directly access the code-behind methods Each input box is a standard HTML input box, and the work begins when you click the Multiply button
Finally, update the InvokePageMethodclass with the following code-behind:
public partial class InvokePageMethod : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
Anthem.Manager.Register(this);
} [Anthem.Method]
public int Multiply(int int1, int int2) {
return (int1 * int2);
}