Working with MagicAJAX
 
Published: 03 May 2006
Unedited - Community Contributed
Abstract
In this article, Azam explains how you can use the MagicAJAX library to make client side calls for the server controls.
by Mohammad Azam
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 44707/ 63

Introduction

In this article, we will look at the MagicAJAX Library which helps make the client side postback calls and provides a smoother user experience.  The article will cover the development of a small application that is used to add and view user specific tasks. 

Downloading MagicAJAX Library

The first step is to download the MagicAjax library.  You can download the library at this link. Once you have downloaded the library, all you need to do is to extract the contents of the zip file so you have access to the .dll files.

Configuring Application to use MagicAJAX

The next step is to configure your application to use the features provided by the Magic AJAX library.  In the design view, right click on the toolbox and select “Choose Items.”   This will open a window which will prompt you to select the library to be added to the application.  Simply select the MagicAJAX.dll and add it to the Toolbox.  This will add various controls to the Toolbox which can be used in the application.

The next configuration is in the web.config file.  Inside the Configuration element add the following section.

Listing 1 – Configuration Settings in web.config

<configSections>
<section name="magicAjax" type="MagicAjax.Configuration.MagicAjaxSectionHandler,MagicAjax"/>
</configSections>
<magicAjaxoutputCompareMode="HashCode" tracing="false">
<pageStore mode="NoStore"
unloadStoredPage="false" cacheTimeout="5"
maxConcurrentPages="5" maxPagesLimitAlert="false"/>
</magicAjax>

Next, add the httpModules section inside the <system.web> section.

Listing 2 – httpModules Settings in Web.config

<httpModules>
<add name="MagicAjax"type="MagicAjax.MagicAjaxModule, MagicAjax"/>
</httpModules>

And that is it.  Now you are ready to use the features provided by the MagicAJAX Library.

Database Design

The database for this application is very simple and consists of only 2 tables.  Please see the database diagram below to have a clear picture of the database design.

Figure 1 – Database Diagram

The next step is to create the required stored procedures.

Listing 3 – Stored Procedures

CREATE PROCEDURE [usp_GetUserTasks] 
 
@UserID int 
 
AS 
 
SELECT TaskID, Description FROM tblTasks t
JOIN tblUsers u ON u.UserID = t.UserID
WHERE u.UserID = @UserID
 
CREATE PROCEDURE [usp_InsertUserTask] 
 
@UserID int, 
@Description nvarchar(50) 
 
AS
 
INSERT INTO tblTasks(UserID, Description) 
VALUES(@UserID, @Description)

I have included the tables and stored procedures' script files with the download at the end of the article.

Scenario

The scenario of this web application is to view and add new tasks for the user.  We will use a DropDownList which will display the names of all the users.  Upon selection of a particular user, we will be able to view all the tasks assigned to that user.

Application Implementation

Now that we are aware of the scenario, let us begin implementing the application.

Populating DropDownList with Users

Our first task is to populate the DropDownList with the names of the users.  Check out the following code which achieves this task.

Listing 4 – Populating DropDownList

private void PopulateDDLNames()
{
  SqlConnection myConnection = newSqlConnection(ConnectionString);
  SqlDataAdapter ad = newSqlDataAdapter("SELECT * FROM tblUsers", myConnection);
  DataSet ds = new DataSet();
  ad.Fill(ds);
  ddlNames.DataSource = ds;
  ddlNames.DataTextField = "Name";
  ddlNames.DataValueField = "UserID";
  ddlNames.DataBind();
}

The PopulateDDLNames method is called in the Page_Load event.

Listing 5 – Page_Load Event

protected void Page_Load(object sender, EventArgse)
{
  if (!Page.IsPostBack)
  {
    BindData();
  }
}
 
private void BindData()
{
  PopulateDDLNames();
}

Now if you run the application, your DropDownList with be populated with the data from the database.  Note that in a production application this would be an excellent place to add some data caching, perhaps with SQL Cache Invalidation.

Implementing the Display Button Click Event

The display button click event is used to display the tasks of a particular user.  The user selection is based on the DropDownList control.  Take a look at the display button click event.

Listing 6 – Display Button Click Event

protected void Btn_DisplayTasks_Click(objectsender, EventArgs e)
{
  int userID =Convert.ToInt32(ddlNames.SelectedValue);
  MyGridView.DataSource = GetUserTasks(userID);
  MyGridView.DataBind();
}

As you may have noticed, the Btn_DisplayTasks calls the GetUserTasks method which returns the tasks based on the user id.

Implementation of the GetUserTasks Method

The GetUserTasks method is responsible for returning the tasks of a particular user.  Take a look at the implementation of the method below:

Listing 7 – GetUserTasks Method

private DataSet GetUserTasks(int userID)
{
  Session["UserID"= userID;
  string sproc = "usp_GetUserTasks";
  SqlConnection myConnection = newSqlConnection(ConnectionString);
  SqlCommand myCommand = new SqlCommand(sproc,myConnection);
  myCommand.CommandType =CommandType.StoredProcedure;
  myCommand.Parameters.AddWithValue("@UserID",userID);
  SqlDataAdapter ad = newSqlDataAdapter(myCommand);
  DataSet ds = new DataSet();
  try
  {
    myConnection.Open();
    ad.Fill(ds);
  }
  catch (Exception ex)
  {
    string exception = ex.Message;
  }
  finally
  {
    myConnection.Close();
    myCommand.Dispose();
  }
  if (ds != null)
    return ds;
  else
    return null;
}

Analysis

The GetUserTasks method simply uses the userID as the parameter to the stored procedure.  The stored procedure returns all the tasks based on that userID and puts the results in the DataSet container.  At the end of the method we simply return the DataSet to the presentation layer.

Adding MagicAJAX to the Application

If you run this application, you will notice that when you click the display button a postback happens and the whole page is reloaded again.  By using MagixAJAX we can remove this reloading behavior and provide the user with a better experience.

In order to add the client postback on the controls, you must put all the controls inside the AjaxPanel control.  Take a look at the HTML code for the page below:

Listing 8 – ASP.NET Code for the Button and GridView

<ajax:AjaxPanel ID="ap"runat="server">
<asp:Button ID="Btn_DisplayTasks"runat="server" OnClick="Btn_DisplayTasks_Click"
Text="Display Tasks" />
<br />
<br />
<br />
<asp:GridView ID="MyGridView" ShowFooter="true" 
runat="server"
AutoGenerateColumns="False" CellPadding="4"
ForeColor="#333333" GridLines="None"
OnSelectedIndexChanged="MyGridView_SelectedIndexChanged"
OnRowCommand="MyGridView_RowCommand" >
<FooterStyle BackColor="#990000"
Font-Bold="True" ForeColor="White" />
<Columns>
<asp:BoundField DataField="TaskID"
HeaderText="TaskID" />
<asp:TemplateField
HeaderText="Description">
<ItemTemplate>
<asp:Label ID="lblDescription"
runat="server" Text='<%# Eval("Description")%>' />
</ItemTemplate>
<FooterTemplate>
<asp:TextBox ID="txtDescription"
runat="server"></asp:TextBox>
<asp:Button ID="Btn_AddDescription"
CommandArgument='<%# Eval("UserID")%>' CommandName="AddDescription"
runat="server" Text="Add Description" />
</FooterTemplate>
</asp:TemplateField>
<asp:CommandField
ShowSelectButton="True" />
</Columns>
<RowStyle BackColor="#FFFBD6"
ForeColor="#333333" />
<SelectedRowStyle
BackColor="#FFCC66" Font-Bold="True"
ForeColor="Navy" />
<PagerStyle BackColor="#FFCC66"
ForeColor="#333333" HorizontalAlign="Center" />
<HeaderStyle BackColor="#990000"
Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle
BackColor="White" />
</asp:GridView>
<ajax:ClientEventTrigger ID="cet"
runat="server" ControlID="Btn_DisplayTasks"
EventName = "Click" />
</ajax:AjaxPanel>

Analysis

The above code represents a simple GridView control and a Button control.  The special thing to note is that both the GridView and the Button are inside the AjaxPanel control.  The AjaxPanel control enables them to make client side postbacks.  The ClientEventTrigger control is used to capture the client event of the control.  The ControlID property is set to “Btn_DisplayTasks” and the EventName is “Click.”  You can also use the keyClientEventWrapper to capture the keypress events inside the input controls.

You can add various columns to the GridView control and since the GridView is inside the AjaxPanel, all the events generated will be handled on the client side.  These events include Selected_IndexChanged, PageIndexChanged, etc.

Downloads

[Download Sample]

Conclusion

In this article, we saw how easily we can use the MagicAjax library and provide the user with a better browsing experience.  I have added the sample code in the download which also contains the MagicAJAX library.



User Comments

Title: MagicAjax in HTTPS   
Name: baxil7
Date: 2009-08-01 8:00:09 PM
Comment:
Sorry
I used magicAjac.dll in my web application
working well in HTTP
but in HTTPS is NOT work
how can I fix this problem?
Title: as new user point of abt magicajex   
Name: nil it
Date: 2009-02-24 12:49:22 AM
Comment:
I was using only AJAX its very vast and also creatful good
design
Title: MajicAjax Library & ClientEventTrigger Control ????   
Name: Shiny
Date: 2007-08-09 3:33:59 AM
Comment:
1. I Have include Magic Ajax dll to my project , now is ther any other settings which i have to do....
2. ClientEventTrigger Control-- what is the purpose of this control....
Title: problem in professional deployment   
Name: harshya
Date: 2007-06-21 11:36:13 AM
Comment:
Hi all
I used magixajax dll for my prof. deployment on third party server but I get following error. any idea of it?
thanks
Harshya



Server Error in '/' Application.
--------------------------------------------------------------------------------

Attempted to access a field that is not accessible by the caller.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.FieldAccessException: Attempted to access a field that is not accessible by the caller.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[FieldAccessException: Attempted to access a field that is not accessible by the caller.]
System.Reflection.RtFieldInfo.PerformVisibilityCheckOnField(IntPtr field, Object target, IntPtr declaringType, FieldAttributes attr, UInt32 invocationFlags) +0
System.Reflection.RtFieldInfo.InternalGetValue(Object obj, Boolean doVisibilityCheck, Boolean doCheckConsistency) +178
System.Reflection.RtFieldInfo.GetValue(Object obj) +8
MagicAjax.AjaxCallHelper.GetPageHiddenDictionary(Page page, String fieldName) +48
MagicAjax.AjaxCallHelper.Page_PreRender(Object sender, EventArgs e) +306
System.Web.UI.Page.OnPreRenderComplete(EventArgs e) +2012740
System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1566




--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.42; ASP.NET Version:2.0.50727.210
Title: A tricky problem   
Name: Jagdish
Date: 2007-06-08 2:33:48 AM
Comment:
Hello,
I have used this MagicAjax.dll in my project
the project have 5 listbox in a .aspx page when the page is loaded only it works for one listbox not other one.
I just want to know whether it works only a single server control..............

Please Reply
Jagdish
Title: Error   
Name: Mohnish Arora
Date: 2007-06-01 5:23:19 AM
Comment:
javascript ajaxcallobject.cs is not set to define location
Title: ClientEventTrigger Control   
Name: Mrs. Wan
Date: 2007-02-08 5:49:38 AM
Comment:
Hi,

I've been referenced MagicAjax.dll. but I can use only AjaxPanel control. So how do I get Ajax:ClientEventTrigger control? Please let me know. Thanks.
Title: about ClientEventtrigger   
Name: yinkehao@163.com
Date: 2007-01-10 11:50:08 PM
Comment:
HI,
I have used one ClientEventtrigger and two AjaxZone whose is AjaxZone1 and Ajaxzone2.AjaxZone1 include one DorpDownList,and AjaxZone2 inlcude the ClientEventtrigger and one Laber.
now I Want to achieve that when i chang the dorpdownList ,the Laber show then DorpDownList's selectitem.text

dorpdownList's AutoPostBack is true;

this is my Event's code

private string ss="-";


protected void ClientEvfenttrigger1_Invoke(object sender, EventArgs e)
{

Label1.Text += ss ;
}
protected void DorpdownList1_SelectedIndexChanged(object sender, EventArgs e)
{
ss += "yy";
}

when i was changed DorpdownList ,the Lable can not show dorpDownlist's selectitem.text and show "-" ,
It's sayed "ss" of variable no transfed when transact DorpDownList_SelectIndexChanged

May is that the ClientEvfenttrigger1_Invoke transact befor then DorpdownList_SelectIdexCHanged
What can I do next ?
Title: thanks   
Name: shahji
Date: 2006-12-26 4:26:25 AM
Comment:
Article helped me much. thanks a lot
Title: Session Problem in Majic Ajax   
Name: Dr.Kash
Date: 2006-11-03 5:42:48 AM
Comment:
hello, I have used majic ajax in my web application. It works fine, i update the grid through the button click and they both are in the majic ajax panel. Now problem comes when the Session of my application expires, then when i click on the button it stucks and after some time blank page arrives. Can any one help that what i have done wrong and how can i prevent this on session expiration. Kindly help me around.
Title: Great   
Name: Tedz
Date: 2006-10-17 6:21:38 AM
Comment:
Very Nice Article.

Can you tell me how to integrated Javascript function in ClientClientEventTrigger. I need event PropertyChange. So when event was called, it will be directed to server side code.

Thanks
Title: AjaxZone with GridView   
Name: MagicAjaxHelp
Date: 2006-10-09 5:10:34 PM
Comment:
Hi

This article helped me in getting started with Magic Ajax control. It is real easy to use.

But I have run in to the following problem:

I have a Gridview with an Add and Remove button. I would like to add rows when the enter key is pressed. I have the code working without the AjaxZone. When I add the AjaxZone around the gridview somehow the rowcommand event of the GridView does not get called. I tried using the ClickEventTrigger and set the ControlID to the GridView and the Event to 'RowCommand'. It doesn't work.

Any help is appreciated.

Thanks.
Title: fileupload   
Name: eddy
Date: 2006-09-08 3:15:48 AM
Comment:
if you bother to read the magicAJAX docs, you can see it's a known limitation.
Title: FileUpload problem   
Name: Energuman
Date: 2006-08-24 9:52:36 AM
Comment:
I guess i'm not the only one to have problem with my UploadFile. What is the problem? I got an FileUpload object in an AjaxPanel, and when i try to get the file i have chosen, i get a "System.NullReferenceException", the object is empty. If i put my FileUpload out of the AjaxPanel, i can successfully obtain my file uploaded. So, i think the problem is due to the AjaxPanel... So i would like to know if it is possible to use the basic FileUpload from ASP, or if there is another one to use instead. I hope my question will not stay without an answer.
Title: FileUpload Problem   
Name: AzamSharp
Date: 2006-08-09 11:37:24 AM
Comment:
Can you explain in detail about the problem?
Title: FileUpload   
Name: Paulo
Date: 2006-08-09 10:00:32 AM
Comment:
I Have the same problem of Noob somebody can help me?
paulo@estudiowebmais.com.br
Title: Need a little help   
Name: Noob
Date: 2006-05-16 8:34:06 AM
Comment:
Hi the article was very informative and it has helped allot. I was wondering if you have managed to use a FileUpload control with ajax, it returns a empty object and I cant seem to get is to work, do you have any idea?
Title: ClientEventTrigger   
Name: AzamSharp
Date: 2006-05-09 11:21:56 AM
Comment:
Hi,

I think you posted this question on the wrong article since ClientEventTrigger is a feature of the UpdatePanel control which comes with the ATLAS framework. The main purpose of the ClientEventTrigger is to refresh the UpdatePanel based on the event of a certain control in this case DropDownList. This means that whenever the DropDownList changes its selected the UpdatePanel will be refreshed and hence the GridView is also refreshed.
Title: I dont understand the usage of control ClientEventTrigger   
Name: vnngoc156@yahoo.com
Date: 2006-05-09 1:01:28 AM
Comment:
Hi Azam,
Your article helps me a lot but can you tell me what is different if we dont use control ClientEventTrigger in above example.
Thanks in advance
Have a good day.
Title: thanks   
Name: mohamed_baddwy@yahoo.com
Date: 2006-05-05 7:45:19 PM
Comment:
thanks Mohamed

your article help me so much.

thanks






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


©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-03-29 2:30:31 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search