I am Raghuveer

In my opinion programming means thinking, and it is fun. My vision is to teach programming in more understandable manner to the students from rural background. I support programming for everyone

Showing posts with label ASP.NET AJAX. Show all posts
Showing posts with label ASP.NET AJAX. Show all posts

Calling ASP.NET Web Services using JQuery AJAX

AJAX has changed the way we developed web sites in the past by giving them responsiveness similar to Desktop applications. In Plain English, AJAX means that instead of waiting for the whole web page to load you can load and display only what you need to. Technically speaking, it’s a technique to communicate with servers through JavaScript asynchronously and handle external data. In this tutorial, I will show you how you can call ASP.NET web service using JQuery, which is the most popular and widely used JavaScript library.

To start communicating with ASP.NET web service through JQuery we first need to implement our web service. Create an ASP.NET web site project in Visual Studio and add an ASP.NET Web Service by right clicking the project name and choosing Add New Item option as shown in the figure below.

Add New Item Dialog

Once the Add New Item dialog box appears, select Web Service (.asmx) item from the list and give web service a suitable name such asDateWebService.asmx. Visual Studio will create a web service (.asmx) and related code behind files in the project. You need to add a method GetDateTime in web service code behind file but keep in mind that we will call this web service from JavaScript so you need to remove comments from the attribute System.Web.Script.Services.ScriptService of your class. The complete code of the web service class is shown below.

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class DateWebService : System.Web.Services.WebService {
public DateWebService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string GetDateTime() {
return DateTime.Now.ToString();
}

}


The web service code is pretty straight forward as there is only one method GetDateTime defined returning the current Date and Time using DateTime.Now property. Before calling the service method using JQuery you need to keep in mind few restrictions on calling service methods from JavaScript. To preventing some security vulnerabilities, ASP.NET service validation layer checks for following two things when service methods are called from JavaScript.

  1. Only POST method can be used to call a web service method. You cannot use HTTP GET.
  2. The HTTP content-type header should be set to the value "application/json".
For those of you who are not familiar with JSON may be wondering what is json and where it came from. So don’t worry I have some basic introduction for you in this tutorial as we will use it in few minutes using JQuery AJAX. In modern AJAX based web applications, when web services are called from client applications, they normally return XML formatted response, which can be parsed and use in JavaScript, but it complicates things for developers. They need a simple data structure which can be used more easily than XML. This is where JavaScript Object Notation (JSON) comes to help us with the following major features.
  1. Lightweight data-interchange format.
  2. Easy for humans to read and write.
  3. Easy for machines to parse and generate.
  4. JSON can be parsed trivially using the JavaScript eval() procedure or using some useful methods in JQuery API.
  5. JSON supports almost all modern languages such as ActionScript, C, C#, ColdFusion, Java, JavaScript, Perl, PHP, Python, Ruby and many more.

Any .NET object you return from web service methods can be serialized in JSON format. To get some familiarity with JSON format, let’s say you have following custom Product object initialized with some properties.

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };


If you will serialize the object in JSON format it will produce the following output:

{
"Name": "Apple",
"Expiry": new Date(1230422400000),
"Price": 3.99,
"Sizes": [
"Small",
"Medium",
"Large"
]
}


You can see from the above output that JSON data structure is very easy to read and understand. If you are a .NET developer and want to learn more about serialization and de-serialization of .NET objects into JSON, I will recommend you to use free JSON.NET library available atjson.codeplex.com.
Let’s come back to our tutorial, we have implemented web service so it’s time to create a web page and call that service using JQuery. Create an ASP.NET web form (.aspx) in your project and add the following button and span tag in web form.

<form id="form1" runat="server">
<input id="Button1" type="button" value="Get Date and Time" />
<br />
<br />
<span id="output" />
</form>


Next add the JQuery library reference and the following JQuery script in the head section of the page.

<script src="Scripts/jquery-1.4.3.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#Button1").click(function() {
$.ajax({
type: "POST",
url: "/ASPNET_WebServices_JQuery/DateWebService.asmx/GetDateTime",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg)
{
$("#output").text(msg.d);
}
});

});
});
</script>

The important lines in the above code are when the $.ajax() method is called inside the Button1 click event handler. $.ajax() method performs an asynchronous HTTP AJAX request and can be customized with many parameters. Some of the parameters I used in the above code are explained below:
type: The type of request you want to make "POST" or "GET". The default value of this parameter is "GET"
url: A string containing the URL to which the request is sent. In the code above, I put the website project name followed by the service file name with extension and then the web method name.
data: This parameter contains the data to be sent to the server. For the GET requests it will be appended to the url although you can change this behavior using processData parameter (not used in the above example). I am using empty braces in the above example as I am not passing any parameters to service methods.
contentType: When sending data to the server, use this content-type. Default is "application/x-www-form-urlencoded". Data will always be transmitted to the server using UTF-8 charset. In the above code, I am explicitly using application/json as the contentType.
dataType: The type of data that you're expecting back from the server. If none is specified, JQuery will intelligently try to get the results, based on the MIME type of the response. The available types are xml, html, script, json, jsonp and text.
success: JQuery $.ajax() method also supports many callback functions, which are invoked at the appropriate during the request process. One of them is a success which is called if the request succeeds.
In this tutorial, I have explained all the options used in this example code above but there are more parameters and options available, and If you are interested to read more about JQuery $.ajax() method please visit the JQuery API documentation available athttp://api.jquery.com/jQuery.ajax.
Build and test your page in the browser, and you will see the server time displayed on the page when you will click the button. If you are using FireFox you can even see the JSON formatted response came from the server in my favorite FireFox plug-in Firebug.

JQuery AJAX ASPNET Web Service

In this tutorial, I tried to give you the basic introduction of calling ASP.NET web service using JQuery AJAX along with some explanation of JSON format. In my future tutorials, I will show you more complex interaction between client and server using JQuery AJAX so please keep visiting my website to learn more about the tips and tricks of latest technologies.

Download Source Code

Using ASP.NET AJAX UpdateProgress Control

When you perform AJAX bases asynchronous postback using ASP.NET UpdatePanel control it performs its job in the background and the user keep working with the other page elements and controls. This is generally what you want to for better user experience but sometimes you have an asynchronous request that takes little longer and you want to show user some visual indication that the request is being processed and the update is under way. In this tutorial I will show you how you can use UpdateProgress control available in ASP.NET AJAX server side controls gallery to simulate the progress indicators.

The UpdateProgress control works in conjunction with the UpdatePanel control and allows you to show a text message or an animated GIF while a time-consuming update is in progress. This control can be added any where on the page and is not need to be added inside UpdatePanel control. When you add the UpdateProgress control to a page, you provide its contents in ProgressTemplate either at design time or in HTML source view. These contents will appear as soon as an asynchronous request is started and disappear as soon as request is finished.

Update Progress Control

The markup below shows you the use of UpdateProgress control in conjunction with UpdatePanel control:

<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<br />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="Button1" runat="server" Text="Next Featured Book"
OnClick="Button1_Click" />
<br />
<br />
<asp:Label ID="Label1" runat="server" Font-Size="14pt">AJAX in Action</asp:Label>
<br />
<br />
<asp:Image ID="Image1" runat="server" ImageUrl="~/images/ajax_in_action.jpg" />
</ContentTemplate>
</asp:UpdatePanel>
<br />
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
<ProgressTemplate>
<img alt="" src="images/progress.gif" /> Loading ...
</ProgressTemplate>
</asp:UpdateProgress>


The button click event handler code below is choosing one random book title along with its image from the NameValueCollection and for making sure this request take little longer I have added Thread.Sleep() method with 2 seconds sleep time.

protected void Button1_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(2000);
NameValueCollection list = new NameValueCollection();
list.Add("AJAX in Action", "images/ajax_in_action.jpg");
list.Add("AJAX Bible", "images/ajax_bible.jpg");
list.Add("Understanding AJAX", "images/understanding_ajax.jpg");
Random r = new Random();
int index = r.Next(0, 3);
Label1.Text = list.Keys[index].ToString();
Image1.ImageUrl = list[index].ToString();
}


The UpdateProgress control has DisplayAfter property that takes number of milliseconds and decide how quickly you want ProgressTemplate to appear inside UpdateProgress control. It also has AssociatedUpdatePanelID property to associate the UpdateProgress control with a particular UpdatePanel control on the page. Once it is associated it will only work asynchronous postback of associated UpdatePanel control.
The following markup demonstrates how you use multiple UpdateProgress control with AssociatedUpdatePanelID property set to different UpdatePanel control.

<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<br />
<table class="style1">
<tr>
<td>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="Button1" runat="server" Text="Show Server Time"
OnClick="Button1_Click" />
<asp:Label ID="Label1" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</td>
<td>
<asp:UpdatePanel ID="UpdatePanel2" runat="server">
<ContentTemplate>
<asp:Button ID="Button2" runat="server" Text="Show Server Time"
OnClick="Button2_Click" />
<asp:Label ID="Label2" runat="server"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
</td>
</tr>
<tr>
<td>
<asp:UpdateProgress ID="UpdateProgress1" runat="server"
AssociatedUpdatePanelID="UpdatePanel1"
>
<ProgressTemplate>
<img alt="" src="images/progress.gif" /> Updating ...
</ProgressTemplate>
</asp:UpdateProgress>
</td>
<td>
<asp:UpdateProgress ID="UpdateProgress2" runat="server"
AssociatedUpdatePanelID="UpdatePanel2"
>
<ProgressTemplate>
<img alt="" src="images/progress.gif" /> Updating ...
</ProgressTemplate>
</asp:UpdateProgress>
</td>
</tr>
</table>


The code behind file with Button Click events is as follows:

protected void Button1_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(2000);
Label1.Text = DateTime.Now.ToString("hh:mm:ss tt");
}
protected void Button2_Click(object sender, EventArgs e)
{
System.Threading.Thread.Sleep(2000);
Label2.Text = DateTime.Now.ToString("hh:mm:ss tt");
}

Following figure shows the output of the above markup.

Multiple Update Progress Controls

Using ASP.NET AJAX Popup Control Extender

ASP.NET AJAX Popup Control can be attached to any ASP.NET control to display additional contents in a popup window. The popup window can display either static contents just like tool tips or can be made more interactive with the help of AJAX UpdatePanel control. It can also have other ASP.NET controls inside which may or may not cause full or AJAX based asynchronous post backs using AJAX UpdatePanel. In this tutorial I will show you how you can use AJAX Popup Control Extender with server side ASP.NET controls.

ASP.NET AJAX Popup Control

To start this tutorial you need to create a blank ASP.NET page that have an instance of AJAX ScriptManager control on top. This control is required to use any AJAX related feature in ASP.NET page and to enable partial page rendering.

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
Then you add a markup of simple message label and a TextBox as shown in the above figure:
Favorite Sport:
<asp:TextBox ID="TextBox1" runat="server" Width="100" />


Then you need to create a popup window which you want to display with the help of AJAX Popup Control Extender. I am using ASP.NET Panel control in this tutorial to popup a RadioButtonList of different sports. You are free to popup any control you want in your application such as ASP.NET Calendar or Login controls.

<asp:Panel ID="Panel1" runat="server">
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:RadioButtonList ID="RadioButtonList1" runat="server"
AutoPostBack="True" BorderColor="#336699" BorderStyle="Solid"
Width="100" BorderWidth="1" BackColor="#dadada"
OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">
<asp:ListItem>Football</asp:ListItem>
<asp:ListItem>Snooker</asp:ListItem>
<asp:ListItem>Tennis</asp:ListItem>
<asp:ListItem>Cricket</asp:ListItem>
</asp:RadioButtonList>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Panel>

In the above markup, I first declared an ASP.NET Panel control. Inside Panel I am using AJAX UpdatePanel control so that any post back occur inside Panel not cause the whole page to be flicker or refresh. UpdatePanel control contains a RadioButtonList control with some ListItems to display different sports names. Notice that the RadioButtonList control’s AutoPostBack property is set to true and an event handler is attached with the OnSelectedIndexChanged event of RadioButtonList. This is the requirement here in this tutorial because I want to update my TextBox with the selected sports name as soon as user selects any sports item from the RadioButtonList control.
Next, you need to add AJAX Popup Control Extender on the page with some basic properties set as shown in the following markup

<ajax:PopupControlExtender ID="PopupControlExtender1" runat="server"
TargetControlID="TextBox1"
PopupControlID="Panel1"
Position="Right"
CommitProperty="value"
OffsetX="3"
>
</ajax:PopupControlExtender>


The explanation of the above properties and some additional properties of AJAX Popup Control Extender is given below:
TargetControlID: The ID of the control you want to attach the popup control with. In the above example I am attaching popup control with TextBox control.
PopupControl: The ID of the control to display as popup window. In the above example I am using Panel control.

Position:
This is optional property and can be set to Left, Right, Top, Bottom or Center. It specifies the relative position of the popup control with respect to target control.

CommitProperty:
This property is also optional and specifies which property will return the result of the popup window. In the above example I put “value” as the value of this property. This is because every time use will select any item from the RadioButtonList control the value of the selected option will be returned from the popup.

CommitScript:
This is another optional property and specifies the additional script to run after setting the result of the popup window.
OffsetX and OffsetY: These two properties specify the number of pixels to offset the popup window horizontally or vertically from its default position as specified by Position property.
The final bit of code you need to finish this tutorial is the SelectedIndexChanged event of RadioButtonList control that hide the popup control by calling its Commit method as soon as user select any item from the RadioButtonList. It also passes the selected value as the parameter of the Commit method so that the value can be returned to target control for display.

protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
{
PopupControlExtender1.Commit(RadioButtonList1.SelectedValue);
}

Display GridView Row Details using ASP.NET AJAX Popup Control

When you display records using ASP.NET GridView control it displays all the columns on the page and often you want to display only few columns in GridView due to the available space on the page. You can easily achieve this functionality by adding your own columns declaratively in the GridView control. But if you want to display other columns in a popup window for each row in the GridView control you need to use AJAX Popup Control with the GridView. In this tutorial I will show you how you can display GridView row details using ASP.NET AJAX Popup control extender.

ASP.NET AJAX Popup Control Extender

To start this tutorial, create a new website in Visual Studio 2008 and add ScriptManager control on the page. This control is required to use any AJAX functionality on ASP.NET page.

<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>

Next you need to add GridView control on the page that has AutoGenerateColumns property set to false to stop ASP.NET to generate columns automatically. You also need to attach OnRowCreated event handler with the grid which I will use later in this tutorial to attach some JavaScript events with a magnify icon to display popup window on mouse over. Following is the complete markup of the GridView control.

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
BorderColor="#336699" BorderStyle="Solid" BorderWidth="1px"
CellPadding="3" Font-Names="Verdana" Font-Size="10pt"
onrowcreated="GridView1_RowCreated">
<Columns>
<asp:BoundField DataField="ProductID" HeaderText="Product ID" />
<asp:BoundField DataField="ProductName" HeaderText="Product Name" />
<asp:TemplateField ItemStyle-Width="40" ItemStyle-HorizontalAlign="Right">
<ItemTemplate>
<asp:Image ID="Image1" runat="server" ImageUrl="~/images/magnify.gif" />
<ajax:PopupControlExtender ID="PopupControlExtender1" runat="server"
PopupControlID="Panel1"
TargetControlID="Image1"
DynamicContextKey='<%# Eval("ProductID") %>'
DynamicControlID="Panel1"
DynamicServiceMethod="GetDynamicContent" Position="Bottom">
</ajax:PopupControlExtender>
</ItemTemplate>
</asp:TemplateField>

</Columns>
<HeaderStyle BackColor="#336699" ForeColor="White" />
</asp:GridView>


The most important thing in the above markup is the TemplateField column definition in which I have used an image control to display magnify icon and ASP.NET AJAX Popup Control Extender.
The PopupControlID property needs the id of the control you want to use as a popup window with AJAX Popup Control in this case I have used Panel control.
The TargetControlID property needs the id of the control that will display the popup window in this case I have used Image1 control that shows magnify icon in the GridView column.
The DynamicServiceMethod property needs the name of the web service method you want to call for every popup window to load additional details from the database.
The DynamicContextKey property needs the dynamic value you want to pass to the dynamic web service method. In this example I am passing ProductID to load more details of the product in the popup window dynamically.
In the end you need a Panel control on the page which will be used as a popup window by the PopupControlExtender control.
<asp:Panel ID="Panel1" runat="server"> </asp:Panel>
Now I am moving to the code behind file of the ASP.NET page that has Page Load event to bind data with the GridView control as shown below:

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadData();
}
}
private void LoadData()
{
string constr = "Server=TestServer;Database=SampleDatabase;uid=test;pwd=test;";
string query = "SELECT ProductID, ProductName FROM Products";
SqlDataAdapter da = new SqlDataAdapter(query, constr);
DataTable table = new DataTable();
da.Fill(table);
GridView1.DataSource = table;
GridView1.DataBind();
}

Next you need the OnRowCreated event definition that will perform two operations during the creation of every data row of the GridView control. First it will find the Popup Extender Control using the FindControl method and will add a unique behavior id with each popup control. Secondly it will find Image control in every row and will attach showPopup() and hidePopup() script with the image onmouseover and onmouseout events. This is required to display popup window on mouse over and hide popup window on mouse out automatically.

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
PopupControlExtender pce = e.Row.FindControl("PopupControlExtender1") as PopupControlExtender;
string behaviorID = "pce_" + e.Row.RowIndex;
pce.BehaviorID = behaviorID;
Image img = (Image)e.Row.FindControl("Image1");
string OnMouseOverScript = string.Format("$find('{0}').showPopup();", behaviorID);
string OnMouseOutScript = string.Format("$find('{0}').hidePopup();", behaviorID);
img.Attributes.Add("onmouseover", OnMouseOverScript);
img.Attributes.Add("onmouseout", OnMouseOutScript);
}
}


In the end, you need the definition of GetDynamicContent service method that will be called by every ASP.NET AJAX Popup Control Extender to load dynamic data from the database and to display additional details in the popup window. The first few lines in the method below are loading additional columns from the Products table in database. The StringBuilder object is created to build html string for the tabular output in the popup window. You can build any type of html for display such as bullets, paragraphs, links etc.

[System.Web.Services.WebMethodAttribute(),
System.Web.Script.Services.ScriptMethodAttribute()]
public static string GetDynamicContent(string contextKey)
{
string constr = "Server=TestServer;Database=SampleDatabase;uid=test;pwd=test;";
string query = "SELECT UnitPrice, UnitsInStock, Description FROM Products WHERE ProductID = " + contextKey;
SqlDataAdapter da = new SqlDataAdapter(query, constr);
DataTable table = new DataTable();
da.Fill(table);
StringBuilder b = new StringBuilder();
b.Append("<table style='background-color:#f3f3f3; border: #336699 3px solid; ");
b.Append("width:350px; font-size:10pt; font-family:Verdana;' cellspacing='0' cellpadding='3'>");
b.Append("<tr><td colspan='3' style='background-color:#336699; color:white;'>");
b.Append("<b>Product Details</b>"); b.Append("</td></tr>");
b.Append("<tr><td style='width:80px;'><b>Unit Price</b></td>");
b.Append("<td style='width:80px;'><b>Stock</b></td>");
b.Append("<td><b>Description</b></td></tr>");
b.Append("<tr>");
b.Append("<td>$" + table.Rows[0]["UnitPrice"].ToString() + "</td>");
b.Append("<td>" + table.Rows[0]["UnitsInStock"].ToString() + "</td>");
b.Append("<td>" + table.Rows[0]["Description"].ToString() + "</td>");
b.Append("</tr>");
b.Append("</table>");
return b.ToString();
}


If you have implemented everything in this tutorial properly you will see the output similar to the figure shown in the start of this tutorial. Please make sure that you have imported the following namespaces in the code file before you run this project.

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Data;
using AjaxControlToolkit;
using System.Text;

Also make sure that you have registered the AjaxControlToolkit in your aspx file using the Register directive as shown below:

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajax" %>

Source:ezzylearning

Using ASP.NET AJAX Accordion Control

ASP.NET AJAX Controls Toolkit contains many useful controls which you can use to provide rich user interface for your website. One such control is Accordion control that allows you to provide outlook style user interface by showing one of the multiple panes. It can be used to create expandable/collapsible navigation bars or to display page contents which user can expand and collapse to view one pane at a time. In this tutorial I will show you how you can implement Accordion control in your ASP.NET websites.

The Accordion control acts as a container of AccordionPane controls and it keeps track of the current AccordionPane and automatically hides any other AccordionPane if it is visible. The AccordionPane controls has Header and Content templates to display heading and contents of the pane. The following figure shows two different views of AccordionPane controls inside Accordion control.

ASP.NET AJAX Accordion Control

To start this tutorial, I have created a new page which has a ScriptManager control on the top. This control is required every time you want to use any AJAX feature or control on you website.

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
Next I have added the following markup for the Accordion control including its nested AccordionPane controls.
<ajax:Accordion ID="Accordion1" runat="server"
HeaderCssClass="Header" ContentCssClass="Contents"
HeaderSelectedCssClass="SelectedHeader"
Font-Names="Verdana" Font-Size="10"
BorderColor="#000000" BorderStyle="Solid" BorderWidth="1"
FramesPerSecond="100" FadeTransitions="true"
TransitionDuration="500">
<Panes>
<ajax:AccordionPane runat="server" ID="AccordionPane1">
<Header>Books</Header>
<Content>
<asp:RadioButtonList ID="RadioButtonList1" runat="server">
<asp:ListItem>HTML</asp:ListItem>
<asp:ListItem>PHP</asp:ListItem>
<asp:ListItem>XML</asp:ListItem>
</asp:RadioButtonList>
</Content>
</ajax:AccordionPane>
<ajax:AccordionPane runat="server" ID="AccordionPane2">
<Header>Movies</Header>
<Content>
<asp:RadioButtonList ID="RadioButtonList2" runat="server">
<asp:ListItem>Titanic</asp:ListItem>
<asp:ListItem>Speed</asp:ListItem>
<asp:ListItem>Shooter</asp:ListItem>
</asp:RadioButtonList>
</Content>
</ajax:AccordionPane>
<ajax:AccordionPane runat="server" ID="AccordionPane3">
<Header>Sports</Header>
<Content>
<asp:RadioButtonList ID="RadioButtonList3" runat="server">
<asp:ListItem>Football</asp:ListItem>
<asp:ListItem>Cricket</asp:ListItem>
<asp:ListItem>Snooker</asp:ListItem>
</asp:RadioButtonList>
</Content>
</ajax:AccordionPane>
</Panes>
</ajax:Accordion>

The following section explains some of the Accordion control properties in detail.
SelectedIndex: As I mentioned above the Accordion control can have multiple AccordionPane controls inside its Panes collection so this property specifies which one of those panes you want to make it visible when the page first loads. You can set it to 0 to display the first or top pane.
HeaderCssClass: This property needs the name of the CSS class that you want to use to style the header section of all the AccordionPane controls inside Accordion control. You can also specify styles for individual AccordionPane controls by settings AccordionPane property instead of setting this property at Accordion control level.
HeaderSelectedCssClass: This property specifies the name of the CSS class you want to use for the selected AccordionPane header. This property can also be set for individual AccordionPane controls.
ContentCssClass: This property specifies the name of the CSS class you want to use to style the content area of the AccordionPane controls.
The CSS classes I have used in this tutorial are shown below.

<style type="text/css">
.Header
{
background-color: #000000;
color: White;
padding: 4px;
font-weight: bold;
}
.SelectedHeader
{
background-color: #808080;
color: White;
padding: 4px;
font-weight: bold;
}
.Contents
{
background-color: #f3f3f3;
padding: 5px;
}
</style>

FadeTransitions: This is a Boolean property to specify whether you need the fading transition effect or standard transition effect for AccordionPane controls.
TransitionDuration: This property needs the number of milliseconds you can to set to increase or decrease the speed of transition effect.
FramesPerSecond: This property specifies the number of frames per second the Accordion control will use to animate the transition between AccordionPane controls.
The Accordion control has Panes collection which contains the collection of AccordionPane controls as you can see in the above markup. I have used simple static text in the Header template and RadioButtonList controls in the Content template of each of the above AccordionPane controls but you are free to use any control or contents you want in your applications.
The Accordion control can also be data bound. It has DataSource and DataSourceID properties which can be set just like other ASP.NET standard data bound controls. The Accordion control also has HeaderTemplate and ContentTemplate properties which you can use to set you data items when Accordion control is data bound.

Using ASP.NET AJAX HoverMenu Control with GridView

Source:ezzylearning

ASP.NET AJAX Controls Toolkit provides many useful controls to ASP.NET developers to build modern rich internet applications. One such control is HoverMenu control that enables you to attach popup menu with any ASP.NET control. It can be used as a simple tooltip which can be attached with a TextBox and showing users what they are suppose to enter in the textbox or like many modern ecommerce shopping applications, it can be used to display larger image of the product when user move mouse on the product thumbnail image. In this tutorial, I will show you how to achieve this functionality using HoverMenu and GridView controls.

ASP.NET AJAX HoverMenu Control

To start this tutorial, I have created a new page which has a ScriptManager control on the top. This control is required every time you want to use any ASP.NET AJAX feature or control on you website.

<asp: ScriptManager ID="ScriptManager1" runat="server"></asp: ScriptManager>
Next, I am adding a GridView control on the page that has AutoGenerateColumns property set to false and adding three BoundField columns and a TemplateField column as shown in the markup below:
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
CellPadding="4" ForeColor="#333333" GridLines="None" BorderColor="#628BD7"
BorderStyle="Solid" BorderWidth="2px">
<Columns>
<asp:BoundField DataField="ProductID" HeaderText="Product ID" />
<asp:BoundField DataField="ProductName" HeaderText="Product Name" />
<asp:BoundField DataField="UnitPrice" HeaderText="Unit Price" />
<asp:TemplateField HeaderText="Picture">
<ItemTemplate>
<asp:Image runat="server" ID="thumbnailImage"
ImageUrl='<%# Eval("Picture") %>' Width="70" Height="60" />
<ajax:HoverMenuExtender ID="HoverMenuExtender1" runat="server"
PopupControlID="popupImage"
TargetControlID="thumbnailImage"
OffsetX="10" OffsetY="5"
PopupPosition="Right"
PopDelay="100" HoverDelay="100">
</ajax:HoverMenuExtender>

<asp:Panel runat="server" ID="popupImage" BorderColor="#628BD7"
BorderStyle="Solid" BorderWidth="7px">
<asp:Image runat="server" ID="mainImage"
ImageUrl='<%# Eval("Picture") %>' />
</asp:Panel>
</ItemTemplate>
</asp:TemplateField>
</Columns>
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
</asp:GridView>

In the markup above, the ItemTemplate of the TemplateField column is first defining the small thumbnail image of the product. This image will be shown to the user when the GridView will be displayed on the page.

<asp:Image runat="server" ID="thumbnailImage"
ImageUrl='<%# Eval("Picture") %>' Width="70" Height="60" />
Next I added HoverMenu control in the ItemTemplate and setting the basic properties of the control.<ajax:HoverMenuExtender ID="HoverMenuExtender1" runat="server"
PopupControlID="popupImage"
TargetControlID="thumbnailImage"
OffsetX="10" OffsetY="5"
PopupPosition="Right"
PopDelay="100" HoverDelay="100">
</ajax:HoverMenuExtender>

Finally I added a Panel control that will be used as a popup window by the HoverMenu control.  This Panel can display any type of contents but for the purpose of this tutorial I am only showing the Product Image using an Image control.

<asp:Panel runat="server" ID="popupImage" BorderColor="#628BD7"
BorderStyle="Solid" BorderWidth="7px">
<asp:Image runat="server" ID="mainImage"
ImageUrl='<%# Eval("Picture") %>' />
</asp:Panel>

The following is the explanation of HoverMenu control properties.
TargetControlID:  This property needs the reference of the target control. HoverMenu display itself automatically when you move mouse on the target control. In this case I have given the id of the small Image control which is defined just above the HoverMenu control.
PopupControlID:  This property needs the id of the control you want to use as a popup window with AJAX HoverMenu Control in this case I have used Panel control which is defined just after the HoverMenu control.
PopupPosition: This is optional property and can be set to Left, Right, Top, Bottom or Center. It specifies the relative position of the HoverMenu control with respect to target control. OffsetX and OffsetY: These two properties specify the number of pixels to offset the HoverMenu control horizontally or vertically from its default position as specified by PopupPosition property.
PopDelay: This property specified the number of milliseconds you want the HoverMenu popup control to remain visible after the user has moved mouse out of the control.
HoverDelay: This property specified the number of milliseconds you want to elapse before the HoverMenu popup control to appears to the user.
HoverCssClass: The name of the CSS class to apply to the target control when the hover menu popup is visible. For brevity, I have not used this property in this tutorial as I directly apply border color and style to the target Panel control.
Animations:  HoverMenu control also supports animations property which you can use to apply generic animation effects to your HoverMenu control.
To complete this tutorial, don’t forget to bind your GridView control with the Products Table in database. The products table I am using for this tutorial has four columns ProductID, ProductName, UnitPrice and Picture. The Picture column is storing the actual image url as string value such as “images/canon_digital_camera.jpg”. Following is the code I am using to bind the GridView with products Table.

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadData();
}
}
private void LoadData()
{
string constr = "Server=TestServer; Database=SampleDB; uid=sa; pwd=123;";
string query = "SELECT ProductID, ProductName, UnitPrice, Picture FROM Products";
SqlDataAdapter da = new SqlDataAdapter(query, constr);
DataTable table = new DataTable();
da.Fill(table); GridView1.DataSource = table;
GridView1.DataBind();
}

Using ASP.NET AJAX ModelPopupExtender from Client Side

Model dialog boxes are very common these days not only in Windows applications but also in web applications. They allow web developers to open new popup windows on the same page without creating a new web page. These popup windows typically ask user some input and temporarily disable the page unless the user dismisses the dialog box. ASP.NET developers can use ModelPopupExtender control available in ASP.NET AJAX controls toolkit to implement model dialog behavior in their web applications. In this tutorial, I will show you how you can use ModelPopupExtender control with client side behavior so that when user performs any action in the dialog box such as button click there is no post back to the server.

AJAX Model Popup Extender

Create a new web site in Visual Studio and open the page in which you want to use ModelPopupExtender control. The first thing you need to add is a CSS class which I will attach with ModelPopupExtender control to make page background transparent and little darker when theModelPopupExtender control will appear on screen. So add this CSS in your page header tag.

<style type="text/css">
.BackgroundStyle
{
background-color: #f3f3f3;
filter: alpha(opacity=50);
opacity: 0.5;
}
</style>

In this tutorial, I want to handle the button clicks inside ModelPopupExtender from client side so I also need a JavaScript function which I will attach with ModelPopupExtender later in this tutorial. Inside my page header tag add the following JavaScript markup.

<script type="text/javascript">
var language = "";
function SetLanguage(value)
{
language = value;
}
function OkButtonClick()
{
$get("Label1").innerHTML = language;
}
</script>

Next, we are moving to our page and you need to add ScriptManager control first which is required to use any ASP.NET AJAX related feature on the page.<asp:ScriptManager ID="ScriptManager1" runat="server" />
Next add a button and a label control on the page. The button will ask user to participate in a quick poll which will be shown in model dialog box and when user will submit the poll by clicking the submit button inside model dialog I will show the results on the label control.

<asp:Button ID="Button1" runat="server" Text="Quick Poll" />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
Next you need to add a Panel control which will be used as a popup window by the ModelPopupExtender control.<asp:Panel ID="Panel1" runat="server" BackColor="#ffffff"
BorderColor="#dadada" BorderStyle="Solid" BorderWidth="4px"
Height="190px" Width="350px" Font-Names="Arial" Font-Size="10pt">
<table cellpadding="10" cellspacing="0" style="width: 100%">
<tr>
<td>
What is your Favorite Programming Language?
</td>
</tr>
<tr>
<td>
<input name="rdLanguage" type="radio" value="Java"
onclick="SetLanguage('Java');" />Java
<br />
<input name="rdLanguage" type="radio" value="VB.NET"
onclick="SetLanguage('VB.NET');" />VB.NET
<br />
<input name="rdLanguage" type="radio" value="C#"
onclick="SetLanguage('C#');" />C#
<br />
</td>
</tr>
<tr>
<td>
<asp:Button ID="Button2" runat="server" Text="Submit" />
<asp:Button ID="Button3" runat="server" Text="Cancel" />
</td>
</tr>
</table>
</asp:Panel>

The above markup inside Panel control is very straight forward. It has three radio button controls and two buttons arranged inside the html table for better layout. The only important thing to notice is how the SetLanguage method defined in the JavaScript above is called from the radio buttons onclick events. This is to set the language variable according to the radio button clicked. Each radio button is setting the language variable according to its own value.

<input name="rdLanguage" type="radio" value="Java"
onclick="SetLanguage('Java');" />
Finally, you need to add the ModelPopupExtender control available in ASP.NET AJAX controls toolkit as follows:<ajax:ModalPopupExtender ID="ModalPopupExtender1" runat="server"
TargetControlID="Button1"
PopupControlID="Panel1"
DropShadow="True"
CancelControlID="Button3"
OkControlID="Button2"
OnOkScript="OkButtonClick()"
BackgroundCssClass="BackgroundStyle" />

The following section explains all the ModelPopupExtender properties in detail:

TargetControlID:
This property needs the id of the target control that will activate the model popup dialog box. I have given the id of the first button control “Button1”.

PopupControlID:
This property needs the id of the control you want to use as a popup window. I have given the reference of the Panel control which ModelPopupExtender will display on screen.

DropShadow:
A Boolean property to add drop shadow to the popup window. I set it to true and you can see a black shadow with popup window in the figure above.

OkControlID:
This property needs the id of the control which will dismiss the model popup dialog box. I have given the reference of Submit Button here because I want the model popup to disappear automatically on Submit button click.

CancelControlID:
This property needs the id of the control that will cancel or dismiss the popup dialog box.

OnOkScript:
This property needs the name of the JavaScript function that will be called automatically when the modal popup is dismissed with the OkControlID. I have given the name of the JavaScript function I defined above so the code in the JavaScript function will run on Submit button click and will set the value of the Label control accordingly.

OnCancelScript:
This property needs the name of the JavaScript function that will be called automatically when modal popup is dismissed with the CancelControlID. In the example above I haven’t used this property because I don’t want to run any script on Cancel button click.
BackgroundCssClass:
This property needs the name of the CSS class to apply to the page background when the modal popup is displayed. I have given the name of the CSS class we defined in the start.

PopupDragHandleControlID:
This property needs the ID of the control which will be used to drag the popup dialog box on screen. Normally, this control is available at the top of the popup window and acts as a title bar for dragging operation. I have not used this property in this tutorial but you can provide dragging feature by setting this property in your applications.

X:
This property can be used to position the model dialog box on screen horizontally by setting the X coordinate of the top/left corner of the modal popup. If you will skip this property the model dialog box will appear centered horizontally.

Y:
This property can be used to position the model dialog box on screen vertically by setting the Y coordinate of the top/left corner of the modal popup. If you will skip this property the model dialog box will appear centered vertically.

RepositionMode:
This property determines whether the popup needs to be repositioned when the window is resized or the page is scrolled by the user.

Using ASP.NET AJAX ModelPopupExtender from Server Side

AJAX Model Popup Extender

Create a new web site in Visual Studio and open the page in which you want to use ModelPopupExtender control. The first thing you need to add is a CSS class which I will attach with ModelPopupExtender control to make page background transparent and darker when theModelPopupExtender control will appear on screen. So add this CSS in your page header tag.

<style type="text/css">
.BackgroundStyle
{
background-color: #f3f3f3;
filter: alpha(opacity=50);
opacity: 0.5;
}
</style>


Next, we are moving to our page and you need to add ScriptManager control first which is required to use any ASP.NET AJAX related feature on the page.
<asp:ScriptManager ID="ScriptManager1" runat="server" />
Next you need to add ASP.NET AJAX UpdatePanel control on the page. This control is required to perform AJAX based asynchronous post backs so that when user click submit button inside model dialog box the whole page does not need to be reloaded.

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>

</ContentTemplate>
</asp:UpdatePanel>

Next add a button and a label control inside the ContentTemplate of the UpdatePanel. The button will ask user to participate in a quick poll which will be shown in model dialog box and when user will submit the poll by clicking the submit button inside model dialog I will show the results on the label control.

<asp:Button ID="Button1" runat="server" Text="Quick Poll" />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
Next you need to add a Panel control inside the ContentTemplate of the UpdatePanel which will be used as a popup window by theModelPopupExtender control.
<asp:Panel ID="Panel1" runat="server" BackColor="#ffffff"
BorderColor="#dadada" BorderStyle="Solid" BorderWidth="4px"
Height="190px" Width="350px" Font-Names="Arial" Font-Size="10pt">
<table cellpadding="10" cellspacing="0" style="width: 100%">
<tr>
<td>
What is your Favorite Programming Language?
</td>
</tr>
<tr>
<td>
<asp:RadioButtonList ID="RadioButtonList1" runat="server">
<asp:ListItem>Java</asp:ListItem>
<asp:ListItem>VB.NET</asp:ListItem>
<asp:ListItem>C#</asp:ListItem>
</asp:RadioButtonList>
</td>
</tr>
<tr>
<td>
<asp:Button ID="Button2" runat="server" Text="Submit"
OnClick="Button2_Click" />
<asp:Button ID="Button3" runat="server" Text="Cancel" />
</td>
</tr>
</table>
</asp:Panel>


The above markup inside Panel control is very straight forward. It has a RadioButtonList control and two buttons arranged inside the html table for better layout. Notice that the submit button has OnClick event handler attached with it which will be defined in code behind file of the page.
Finally, you need to add the ASP.NET AJAX ModelPopupExtender control inside the ContentTemplate of the UpdatePanel control as follows:

<ajax:ModalPopupExtender ID="ModalPopupExtender1" runat="server"
PopupControlID="Panel1"
DropShadow="True"
TargetControlID="Button1"
CancelControlID="Button3"
BackgroundCssClass="BackgroundStyle" />

The following section explains all the ModelPopupExtender properties in detail:
TargetControlID: This property needs the id of the target control that will activate the model popup dialog box. I have given the id of the first button control “Button1”.
PopupControlID: This property needs the id of the control you want to use as a popup window. I have given the reference of the Panel control which ModelPopupExtender will display on screen.
DropShadow: A Boolean property to add drop shadow to the popup window. I set it to true and you can see a black shadow with popup window in the figure above.
OkControlID: This property needs the id of the control which will dismiss the model popup dialog box. I am not using this property in this tutorial because I want to handle submit button click event on the server side.
CancelControlID: This property needs the id of the control that will cancel or dismiss the popup dialog box.
OnOkScript: This property needs the name of the JavaScript function that will be called automatically when the modal popup is dismissed with the OkControlID. You don’t need to set this property if you want to handle submit button click in the server side code with a post back.
OnCancelScript: This property needs the name of the JavaScript function that will be called automatically when modal popup is dismissed with the CancelControlID. In the example above I haven’t used this property because I don’t want to run any script on Cancel button click.
BackgroundCssClass: This property needs the name of the CSS class to apply to the page background when the modal popup is displayed. I have given the name of the CSS class we defined in the start.
PopupDragHandleControlID: This property needs the ID of the control which will be used to drag the popup dialog box on screen. Normally, this control is available at the top of the popup window and acts as a title bar for dragging operation. I have not used this property in this tutorial but you can provide dragging feature by setting this property in your applications.
X: This property can be used to position the model dialog box on screen horizontally by setting the X coordinate of the top/left corner of the modal popup. If you will skip this property the model dialog box will appear centered horizontally.
Y: This property can be used to position the model dialog box on screen vertically by setting the Y coordinate of the top/left corner of the modal popup. If you will skip this property the model dialog box will appear centered vertically.
RepositionMode: This property determines whether the popup needs to be repositioned when the window is resized or the page is scrolled by the user.
In the end, add the following code in the page code behind file to handle Submit button click event. That’s it, Test your page in the browser and you will see the model dialog box similar to the above figure. Select any language option from the model dialog box and click submit button. You will notice the label on the page updated with your selected language without a full post back.

protected void Button2_Click(object sender, EventArgs e)
{
Label1.Text = RadioButtonList1.SelectedItem.Text;
}