AspAlliance.com LogoASPAlliance: Articles, reviews, and samples for .NET Developers
URL:
http://aspalliance.com/articleViewer.aspx?aId=835&pId=-1
Working with MagicAJAX
page
by Mohammad Azam
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 44570/ 76

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.



©Copyright 1998-2024 ASPAlliance.com  |  Page Processed at 2024-04-26 9:20:52 AM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search