Create Client Controls in ASP.NET 2.0 AJAX 1.0 Extensions
page 6 of 9
by Bilal Haidar
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 40115/ 98

Running the Controls all together

The first thing to do in order to show the grid on the page is create the grid client control and bind data to it as shown in the code below.

Listing 22

var app = Sys.Application;
app.add_load(applicationLoadHandler);
 
function applicationLoadHandler(sender, args)
{
  var Contacts = $create(Bhaidar.AJAXControls.ContactControl,  // Type
  null,  // Properties
  {
    editRecord: EditRecord, deleteRecord: DeleteRecord
  }
  , // Events
  null// References
  $get("ContactControl")); // Element
 
  // Wire up the add new context button click event handler
  $addHandler($get('btnNewContact'), 'click', Function.createDelegate(this,
    AddNewContact));
 
  // Bind the Contact Control data
  GetContactList();
}

The code handles the pageLoad function that is part of the Application object and creates the ContactControl by using the $create method. Using the $create method we can pass in the Type of the control we are creating in this case Bhaidar.AJAXControls.ContactControl, define properties in this case no properties are defined, attach event handler to events, in this case the code attaches two events editRecord and DeleteRecord to two event handlers respectively, and finally set the DOM element that this control is bound to. In this case the ContactControl is bound to a div element on the page.

Listing 23

<div id="ContactControl" style="width:100%"></div>

Next, a handler is added to the button that creates a new contact record. The event handler is included which is AddNewContact function.

Finally, a call to the GetContactList function is done. This function is responsible of retrieving data from the AJAX service and binding it to the grid client controls.

Listing 24

function GetContactList()
{    
  var startIndex = currentPage;
  var endIndex = pageSize   
  Bhaidar.Services.ContactsService.GetContactList
   (startIndex, endIndex, OnDataReady);
}

The success callback function that will be executed when the response is back from the server is as follows:

Listing 25

function OnDataReady(result, userContext, methodName)
{
  var comp = $find("ContactControl");
  comp.set_dataSource(result);
  comp.dataBind();
}

The function gets a reference to the grid client control already created on the page using the $find function, then sets the data source property to the data returned from the AJAX service, in this case a List<Contact>. Finally, a call to the dataBind() function is issued to render the grid client control and display all the records returned from the server.

If we go back to the renderControl function inside the ContactControl, you will notice something.

Listing 26

this._dataSource[i].FirstName

After setting the data source property to the data returned from the server, the data source now contains all the data on the client side. To access a contact record, simply use an indexer. Every item returned by an indexer represents an object of type Contact. That is why you see in the above code how easy it is to access any property inside the Contact class.

Once the New Contact button is clicked, the AddNewContact function will be fired according to the binding shown above.

Listing 27

function AddNewContact() {
    var newContact= $create(
        Bhaidar.AJAXControls.ContactRecordControl,  // Type
        null,                                       // Properties
        {click: HandleGridUpdate},                  // Events
        null,                                       // References
        $get("ContactRecordControl"));              // Element
    
    return false;
}

What the method does is simply create a new ContactRecordControl and add it to the page. There is nothing new in defining this control; the code simply attaches the HandleGridUpdate function to the click event defined on the control.

The HandleGridUpdate is defined as follows:

Listing 28

function HandleGridUpdate(sender, args)
{
  // Get the fields from the page
  var errorMsg = '';
 
  var txtFirstName = $get("txtFirstName");
  if ((txtFirstName.value == null) || (txtFirstName.value == ''))
    errorMsg += "First Name is required.\r\n";
 
  var txtLastName = $get("txtLastName");
  if ((txtLastName.value == null) || (txtLastName.value == ''))
    errorMsg += "Last Name is required.\r\n";
 
  var txtEmail = $get("txtEmail");
  if ((txtEmail.value == null) || (txtEmail.value == ''))
    errorMsg += "Email is required.\r\n";
 
  if (errorMsg != '')
    alert(errorMsg);
  else
  {
    ShowUpdateProgress();
 
    if (null == args.get_data())
    {
     // Add new record
      Bhaidar.Services.ContactsService.AddNewContact(txtFirstName.value,
        txtLastName.value, txtEmail.value,  // Parameters
      OnAddNewContactCompleted); // Success Callback
    }
    else
    {
      // Update old record
      Bhaidar.Services.ContactsService.UpdateContact(parseInt(args.get_data()
        .ContactID), txtEmail.value,  // Parameters
      OnUpdateContactCompleted); // Success Callback
    }
  }
}

The function starts by doing some validation on the fields. It then decides whether we are adding a new record or editing an existing record. The args parameter is null in the case of adding a new row and in case of editing a row, it contains the row that is being edited.

The EditRecord function is fired when the edit button is clicked on the grid client control.

Listing 29

function EditRecord(sender, args)
{
  if (args)
  {
    var newContact = $create(Bhaidar.AJAXControls.ContactRecordControl,  // Type
    {
      dataSource: args.get_data()
    }
    ,  // Properties
    {
      click: HandleGridUpdate
    }
    ,  // Events
    null,  // References
    $get("ContactRecordControl")); // Element
  }
}

The function simply creates a new instance of the ContactRecordControl passing in the value of the dataSource property to be args.get_data(). In this case the dataSource is bound to the contact record representing the row to be edited on the grid control. The function to handle the click event is the HandleGridUpdate, which is defined and explained above. That method handles both edit and new actions. Figure 3 shows the page when a record is in the edit mode.

Figure 3

3.gif

The DeleteRecord event handler handles the delete event on the grid client control.

Listing 30

function DeleteRecord(sender, args)
{
  Bhaidar.Services.ContactsService.DeleteContact(args.get_data(),  // Parameters
  OnDeleteContactCompleted);
  // Success Callback
}
}

It simply calls the AJAX service to delete a record passing in the contact ID, which is stored inside the args parameter get_data() property.

There are still other methods that represent the success callbacks of the AJAX service method calls that you can simply read and understand from the downloadable code of this article.


View Entire Article

User Comments

Title: gsdfg   
Name: nikesh
Date: 2009-12-24 6:21:47 AM
Comment:
not bad
Title: Mr   
Name: Malcolm Swaine
Date: 2008-07-09 6:24:45 PM
Comment:
"A control is already associated with the element." - try removing the Ajax Functionality and this goes away ... quick workaround
Title: edit data error   
Name: jfliuyun
Date: 2007-06-21 4:26:44 PM
Comment:
when first click editimage everything is ok,but before you submit the data ,you click editimage throw error "A control is already associated with the element." can you tell me what happened,and how to result it,thanks
Title: Yes it does!   
Name: Muhammad Mosa
Date: 2007-06-21 8:10:15 AM
Comment:
Yes it does! at least you closed the door. I was thinking of another way and want to make sure there is no other way
Title: Re: Muhammad   
Name: Bilal Haidar [MVP]
Date: 2007-06-20 6:54:11 AM
Comment:
In AJAX 1.0 you only have two ways to interact with methods on the server:
1- WS methods
2- Page static methods

In the second option, you can place a static method on the page, inside it you can directly access your API the way you want. Does this help you?

Regards
Title: Bind The Control with a data layer   
Name: Muhammad Mosa
Date: 2007-06-20 3:56:54 AM
Comment:
No, this is not my target. sorry for this. what I mean I have Business Logic Rule Library. I want to use this library's methods to bind data to the AJAX control. Just as in your sample, but instead of using WS I want to use normal library
Title: Re: Bind The Control with a data layer   
Name: Bilal Haidar [MVP]
Date: 2007-06-19 3:47:13 PM
Comment:
I guess I didn't get your question right!

Do you mean you want to use WS not developed in .NET? Please correct me if I am wrong!

Thanks
Title: Bind The control with a data layer   
Name: Muhammad Mosa
Date: 2007-06-19 1:26:28 PM
Comment:
Well, we are on the same boat then. Ok in this sample, do you have any idea how can I bind the control to a data layer method that is not a WS method?!
Keep the good work brother
Title: Re: Carlito   
Name: Bilal Haidar [MVP]
Date: 2007-06-19 1:09:59 PM
Comment:
Carlito,
I will be checking on that and get back to you here on this article!
Regards
Title: Re: Muhammad Mosa   
Name: Bilal Haidar [MVP]
Date: 2007-06-19 1:07:59 PM
Comment:
Hello Muhammad,
We never use WS as a data layer. I can speak on myself, it is only for demonstration purpose that I embed the nasty DB work inside my WS. Just to save some time!
But in real projects, WS should only be an interface for your application and all your logic (BL and DAL) should be in a seperate API!!

Hope this answers your question!

Regards
Title: Mozilla compatibility   
Name: Carlito
Date: 2007-06-19 12:30:41 PM
Comment:
Hi, I was just trying your sample code which seems to work well with IE but not so well with Firefox.
It seems whenever I click on 'New Contact', the new contact sections shows for a second then disappears and the page reloads the contact list again...
Title: Nice By why always Web Services?!   
Name: Muhammad Mosa
Date: 2007-06-19 9:41:23 AM
Comment:
Wonderful as usual Bilal. I have one comment but it is not on the article it is general. Every time I read something about ASP.NET AJAX -well not everything- they just present Web Services as the data service to retrive data! While in most cases we don't use web services unless it is required. I mean I'm not going to use Web Service just to act as a data layer, I already have my data layer library!
In this I'm not going to use Web Service! you may suggest to use static web methods on the page itself, well is there are any other alternatives?!






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-05-18 11:33:36 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search