Login | Register   
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Using the Ajax.NET Framework : Page 6

What developer wants to spend hours manually writing Ajax plumbing when the Ajax.NET framework does this for free?


advertisement
Add Element Methods
Element methods are JavaScript functions that are meant to act much like protected member variables in an ASP.NET page. These functions act as a wrapper to the input control or element on the page so you only have to find the control on the page once. Often you will see code littered with unnecessary uses of the document.getElementById method. Using element methods will clean up your code and help you avoid redundancy. Listing 6 shows an example of how to use these functions.

Create an element method for each of the controls you will access on the page. Notice, just as in the standard .NET code behind variables, you'll name your element methods the same as the element ID defined in the HTML.

Add Behavior Methods
The next set of functions you will add perform the work of finding the tasks and either updating or deleting the objects from the collection. These functions are responsible for using the functions I created in the code behind in Listing 6.

The GetTaskById function shown below passes in the task ID to the server-side method of the same name. Once the client recognizes a response, it calls the GetTaskById_CallBack function.

function GetTaskById(id) { _default.GetTaskById(id,GetTaskById_CallBack); } function GetTaskById_CallBack(response) { var id; var title; var description; var task; if(IsValidResponseValue(response)) { task = response.value; hdnId().value = task.Id; txtTitle().value = task.Title; txtDescription().value = task.Description; } else { alert("Task not found."); } }

The GetTaskById_CallBack function first uses the IsValidResponse utility method to ensure a valid response from the server. If the server sends the expected response, the requested ID, title, and description are placed into the value properties of the input control objects by this function. If the task is not found, the user is notified via a JavaScript alert.

The DeleteTask method takes the Task ID as the only argument. This method will then contact the server and run the implementation for DeleteTask server-side. Remember that the server will return the updated collection when an item is deleted from the list. With the collection returned from the server, you do not need to write any additional code to finish this process-all you need to do is to display the task information to the user. The GetTasks_CallBack method works perfectly in this instance. GetTasks_CallBack will pass the response to the LoadTasks method, which will apply the template to each task item and display the update list to the user.

function DeleteTask(id) { _default.DeleteTask(id,DeleteTask_CallBack); } function DeleteTask_CallBack(response) { GetTasks_CallBack(response); divTaskInput().style.display = "none"; }

EditTask calls the GetTaskById method you already implemented. This will find the task and display the values in the input controls on the page. Next the input box is displayed to the user by setting the DIV's display property off the style object equal to block, thus showing the box to the user. Finally, the method sets focus to the title control to make editing the task easy for the user.



function EditTask(id) { GetTaskById(id); divTaskInput().style.display = "block"; txtTitle().focus(); }

Now when you run the page you will see an edit link and a delete link. If you click the delete link, the task item is successfully deleted from the list and the page is updated. If you click on the edit link, an input box will appear with the task information populated in the input controls. The Save and Close buttons are not yet implemented, so clicking on those buttons at this time will result in JavaScript errors.

Implement the Task Editor Controls
Now you must implement the behavior that will send changes to the server to update the collection store.

The following instructions will direct you to implement the Save and Close buttons in the task editor. The last feature you'll add to the application is the ability to add a task. The following code will implement some of this logic as the Save method is concerned with saving task data whether or not it is a new task or an update to a task.

Update TaskCollection Class
Adding the UpdateTask method as shown below requires the task ID, the update title value, and the updated description value as arguments.

public bool UpdateTask(Guid id, string title, string description) { bool success = false; foreach(Task task in this) { if(task.Id == id) { task.Title = title; task.Description = description; success = true; break; } } return success; }

Once the desired task is located in the collection the updates are made to the title and description.

If the task is found the method returns true, if the task is not in the list the method returns false.

Update _default Class
Adding the EditTask method requires the task ID, title, and description as arguments. Please notice that I put the call to System.Threading.Thread.Sleep(5000) in this method simply for demonstration purposes. Calling the Sleep method will force the application to wait for five seconds before continuing on with its processing. This simulates a long server-side transaction and shows how the browser can deal with that type of latency. Finally, the data received by the page is passed to the Task object to update the task.

[Ajax.AjaxMethod()] public bool EditTask(string id, string title, string description) { // The following line is for // demo purposes only System.Threading.Thread.Sleep(5000); Guid gId; gId = new Guid(id); return WebAppConfig.Tasks.UpdateTask(gId, title,description); }

The AddTask method creates a new task object from the passed in title and description and then adds the new object to the task collection.

[Ajax.AjaxMethod()] public bool AddTask(string title, string description) { // The following line is for demo // purposes only System.Threading.Thread.Sleep(5000); Task task; task = new Task(title,description); WebAppConfig.Tasks.Add(task); return true; }

Update JavaScript
Remember that the Save button persists task information on the server whether or not a task is new or recently edited. The order of business is to decide if the task is new or if the user clicked the edit link.

When the edit link is clicked the task information is queried on the server and the values are filled in the input controls.

The btnSave_Click method shown below handles the logic to save task information on the server.

function btnSave_Click(id,title,description) { var id; if(hdnId().value != "") { _default.EditTask(hdnId().value,txtTitle().value, txtDescription().value,EditTask_CallBack); } else {_ default.AddTask(txtTitle().value, txtDescription().value,EditTask_CallBack); } divTaskInput().style.display = "none"; divStatus().style.display = "block"; }

If the task ID hidden control has a value, then the application knows that it's dealing with an existing task. The EditTask method on the server is then called, passing in the task ID and the updated title and description. The final argument directs the browser to call EditTask_CallBack when it recognizes a response from the server.

The EditTask_CallBack method checks for a valid response, hides the status message, and then loads the updated task collection on to the page.

If the page determines the task is new, it calls the AddTask method on the server. Once the client receives a response from the server the EditTask_CallBack method is also called for this operation.

Finally, the btnSave_Click method updates the user interface to hide the task editor and show the status message on the screen. The callback methods hide the status message when the server operation is complete.

The EditTask_CallBack method will look for a valid response. If everything went as planned, the status message is hidden and the browser is directed to display the updated task collection to the user.

function EditTask_CallBack(response) { if(IsValidResponseValue(response)) Then { divStatus().style.display = "none"; GetTasks(); } }

The btnClose_Click method simply hides the task editor from the user.

function btnClose_Click() { divTaskInput().style.display = "none"; }

Now when users click the Edit button the task editor will appear. When they click the Save button, a status message appears at the bottom of the browser window that persists until the client hears back from the server indicating the process is complete. Figure 5 shows how the status message will appear at the bottom of the browser window.

 
Figure 5: The task system shows a status message at the bottom of the screen during long server-side operations.
The application can now display the tasks to the user and allow the user to edit and delete tasks. The system is missing one last feature. The next section will grant the user the ability to add a new task to the list.

Implement Add Task
At this point you've written most of the code necessary to make the application work. Adding the "add task" feature from here is easy.

First you want to update the HTML document. Return to default.aspx, switch to the HTML view, and make the following changes to the file.

The HTML requires adding a link to the page that will tell the application you are creating a new task and then display the task editor to the user.

Locate the point in the file where the H1 and the DIV identified as divTasks meet. Place the new line of code shown in the below snippet between these two lines.

<h1>Tasks</h1> <a href="javascript:void(0);" id="lnkAdd" name="lnkAdd" onclick="lnkAdd_Click();">Add Task</a> <div id="divTasks"></div>

The addition of this anchor tag will display an Add Task button to the page and direct the browser to call lnkAdd_Click when anyone clicks the link.

Update the JavaScript
The ClearTaskInput method will clear the controls in the task editor, priming the system for a new task.

function ClearTaskInput() { hdnId().value = ""; txtTitle().value = ""; txtDescription().value = ""; }

The btnAdd_Click method will clear the task editor of any previous values, display the task editor to the user, and set focus to the title control.

function lnkAdd_Click() { ClearTaskInput(); divTaskInput().style.display = "block"; txtTitle().focus(); }

You now have a fully functioning task system using the Ajax.NET Framework.

Now that you have had an opportunity to use the Ajax.NET Framework you'll notice that there are a few steps in traditional Ajax development that are unnecessary. When a response is returned from the server you have a response object filled with the returned data. At no time did you have to parse through XML markup or manually poll the server for ready states. The Ajax.NET Framework saves developers time and simplifies the process of creating Ajax applications.



Craig Shoemaker is a software engineer for PDSA, Inc., a Microsoft Partner in Southern California. With over 10 years experience in Web development, he brings a unique perspective to tying together front- and back-end development. Craig is also the host of the Polymorphic Podcast, a weekly audio show about object-oriented development, architecture, and best practices in .NET.
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap