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. Show all posts
Showing posts with label ASP.NET. Show all posts

Sorting ASP.NET GridView Control using JQuery Tablesorter Plugin

Displaying records in a tabular format is very common functionality of modern websites. Almost all the websites you visit these days have data to display in a table or datagrid and most of them also required the functionality of sorting records based on any column. Last week I had a chance to work with one of a popular JQuery plugin called Tablesorter and I was so impressed that I decided to write a full tutorial on it. In this tutorial, I will show you how you can use JQuery Tablesorter plugin with ASP.NET GridView control to provide client side sorting functionality to your site visitors.
Sorting ASP.NET GridView Control with JQuery Tablesorter Plugin
If you want to play with the Tablesorter JQuery plugin yourself with all the customized options, make sure you download the latest version ofTablesorter plugin from the following URL.
http://tablesorter.com/docs
Create a new ASP.NET website and drag a GridView control on the page. Disable the automatic columns generation by usingAutoGenerateColumns property and add some bound fields inside the GridView Columns collection. For this tutorial, make sure your GridView control HTML markup looks similar to the following:
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333"
GridLines="Horizontal" Font-Size="9pt" Font-Names="Arial"
AutoGenerateColumns="False" BorderColor="#dadada"
BorderStyle="Solid" BorderWidth="1px">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID"
ItemStyle-Width="40" />
<asp:BoundField DataField="Name" HeaderText="Name"
ItemStyle-Width="80" />
<asp:BoundField DataField="Fee" DataFormatString="{0:n0}" HeaderText="Fee"
ItemStyle-Width="60" />
<asp:BoundField DataField="Price" DataFormatString="{0:c}"
HeaderText="Price" ItemStyle-Width="60" />
<asp:BoundField DataField="Discount" DataFormatString="{0:p1}"
HeaderText="Discount" ItemStyle-Width="70" />
<asp:BoundField DataField="Difference" DataFormatString="{0:n1}"
HeaderText="Difference" ItemStyle-Width="80" />
<asp:BoundField DataField="Date" DataFormatString="{0:MMM dd, yyyy}"
HeaderText="Date" ItemStyle-Width="100" />
<asp:BoundField DataField="OnSale" HeaderText="OnSale"
ItemStyle-Width="60" />
</Columns>
</asp:GridView>
As you can see bound fields are bound with columns such as ID, Name, Fee and so on. These columns are coming from a temporary DataTable object which I have filled and bind with GridView in the Page Load event. Following code shows the Page Load event and the code required to fill DataTable.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
private void BindData()
{
int[] ids = {12, 13, 14, 15, 16};
string[] names = {"Alice", "James", "Peter", "Simon", "David"};
int[] fee = { 2299, 5123, 7564, 9595, 1600 };
decimal[] prices = { 12.99m, 122.23m, 25.64m, 66.85m, 1.60m };
decimal[] discounts = { 0.2m, 0.194m, 0.4564m, 0.209m, 0.310m };
decimal[] differences = { -12m, 19.4m, -45.64m, 200.9m, 41.60m };
string[] dates = { "04-12-2010", "07-23-2010", "07-14-2009", "12-12-2010", "11-03-2019" };
bool[] onSale = { true, false, true, true, false };
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(System.Int32));
table.Columns.Add("Name", typeof(System.String));
table.Columns.Add("Fee", typeof(System.Decimal));
table.Columns.Add("Price", typeof(System.Decimal));
table.Columns.Add("Discount", typeof(System.Decimal));
table.Columns.Add("Difference", typeof(System.Int32));
table.Columns.Add("Date", typeof(System.DateTime));
table.Columns.Add("OnSale", typeof(System.Boolean));
for (int i = 0; i < 5; i++)
{
DataRow row = table.NewRow();
row["ID"] = ids[i];
row["Name"] = names[i];
row["Fee"] = fee[i];
row["Price"] = prices[i];
row["Discount"] = discounts[i];
row["Difference"] = differences[i];
row["Date"] = DateTime.Parse(dates[i]);
row["OnSale"] = onSale[i];
table.Rows.Add(row);
}
GridView1.DataSource = table;
GridView1.DataBind();
GridView1.UseAccessibleHeader = true;
GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;
}

Before you build and test your web page, add the following CSS styles inside page head section to add some spice to your GridView.
<style type="text/css">
th
{
cursor:pointer;
background-color:#dadada;
color:Black;
font-weight:bold;
text-align:left;
}
th.headerSortUp
{
background-image: url(images/asc.gif);
background-position: right center;
background-repeat:no-repeat;
}
th.headerSortDown
{
background-image: url(images/desc.gif);
background-position: right center;
background-repeat:no-repeat;
}
td
{
border-bottom: solid 1px #dadada;
}
</style>

Add the following JQuery and Tablesorter javascript files references inside page head section.
<script src="scripts/jquery-1.4.3.min.js" type="text/javascript"></script>
<script src="scripts/jquery.tablesorter.min.js" type="text/javascript"></script>
Click here for table sorter plugin
Finally call the tablesorter function on GridView to make your GridVeiw sortable.
<script type="text/javascript">
$(document).ready(function() {
$("#GridView1").tablesorter();
});
</script>

You can see how easy is to add client side sorting functionality to your GridView using the Tablesorter plugin. You just need to call a single function Tablesorter to implement basic sorting. However, there are many other options to customize the sorting functionality, and I will recommend you to visit the Tablesorter plugin home page to read the documentation for all the available options.

Encrypting and Decrypting Query Strings in asp.net

Introduction

We often pass values between pages in the form of a query string as key-value pairs. Query string is the easiest way and most widely practiced mechanism of transferring small pieces of data between web pages. The end-user may change the value in the query string to play around with the application, and at the same time, it leads to compromising the security and data integrity of the system. So the solution is encrypting the query strings.

Following is the simple way of encryption and decryption mechanism in asp.net

First I created two methods for encryption and decryption

Encrypt the string

        private string Encrypt(string stringToEncrypt)
         {
             byte[] inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
             byte[] rgbIV = { 0x21, 0x43, 0x56, 0x87, 0x10, 0xfd, 0xea, 0x1c };
             byte[] key = { };
             try
             {
                 key = System.Text.Encoding.UTF8.GetBytes("A0D1nX0Q");
                 DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                 MemoryStream ms = new MemoryStream();
                 CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(key, rgbIV), CryptoStreamMode.Write);
                 cs.Write(inputByteArray, 0, inputByteArray.Length);
                 cs.FlushFinalBlock();
                 return Convert.ToBase64String(ms.ToArray());
             }
             catch (Exception e)
             {
                 return e.Message;
             }
         }         

Decrypt the encrypted string





        private string Decrypt(string EncryptedText)
{
byte[] inputByteArray = new byte[EncryptedText.Length + 1];
byte[] rgbIV = { 0x21, 0x43, 0x56, 0x87, 0x10, 0xfd, 0xea, 0x1c };
byte[] key = { };

try
{
key = System.Text.Encoding.UTF8.GetBytes("A0D1nX0Q");
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
inputByteArray = Convert.FromBase64String(EncryptedText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(key, rgbIV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
System.Text.Encoding encoding = System.Text.Encoding.UTF8;
return encoding.GetString(ms.ToArray());
}
catch (Exception e)
{
return e.Message;
}
}

It is better practice to encode the encrypted string before adding it to the URL like following, you can pass any number of parameters as you can (ex: OrderId=1&Name=RV )





   var addressLink = "http://abcxyz.com/abc.aspx?" + HttpUtility.UrlEncode(Encrypt(string.Format("OrderId={0}", orderId)));

Encryption is done, now we have to decrypt the encrypted string whenever we need, like following





   string str = "";
str = Request.RawUrl;
   var qs = Decrypt(HttpUtility.UrlDecode(str.Substring(strReq.IndexOf('?') + 1)));

Parse the returned string according to the parameters you have passed in above expression.

Remove Hyperlink from ASP.NET TreeView Control Nodes

A simple post on how to change the TreeView node property to plain text instead of hyperlinks.

ASP.NET Tree view control rendered as HTML Table – TR –TD  elements. Each of the node are been represented as hyperlinks. Some times you may not want that fields as hyperlink and you want to be those nodes should be represent as static text. Many of the developer did the same using  font style or css style change of the node, but it can be done very easily.  In this small blog  post I am going to describe how you can represent a tree view node as simple text instead of hyperlink.

This can be done very easily using Tree Nodes, SelectionAction properties. SelectionAction having 4 different values, they are.

3

Select is the default option which marked node as hyperlinked and on selection of the node, it raised SelectedNodeChanged event.  For Expand Option, TreeNodeExpanded event will be raised while expanding the node. “SelectExpand” raised both the SelectedNodeChanged and  TreeNodeExpanded  events. Now if you don’t want to make the node as simple text, just change the SelectionAction properties to “None”.

1

Changing the SelectAction Dynamically

Above image showing how you can change the “SelectionAction” properties while creating a TreeView manually. But most of the time bind the data from a data source with tree view dynamically, for that you can use bellow code snippet.

2

So, what does this “Select” and “None” really make change internally ? Yes, when you are using Selection Action as “Select” Treeview Nodes rendered as HTML hyperlink in UI but for the “None” it rendered as "Span

Below image showing the “Span” element of TreeNode for “SelectionAction=”None””

4

Below image showing the hyperlink mode of TreeNode for “SelectionAction=”Select””

5

ASP.NET GridView Mouseover Hover Effect using JQuery

JQuery API has many CSS related functions, which can be used to create many UI effects in the modern web applications. The most common of those methods are addClass, removeClass and toggleClass, which add, remove or toggle CSS classes to any matched element. In this Tutorial, I will show you how you can create a simple mouseover hover effect on ASP.NET GridView Rows using JQuery CSS related methods.

To get things started, create an ASP.NET website and add a GridView control to the page from the Data Category in Toolbox. The following code shows the GridView control I am using for the demonstration of this tutorial. Please set the appropriate properties as shown in the code snippet below.

<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" BackColor="White" Font-Size="10"
Font-Names="Verdana" BorderColor="#000000" BorderStyle="Solid" BorderWidth="1px"
CellPadding="3" Width="400px" CellSpacing="0" GridLines="Horizontal">
</asp:GridView>

</form>

Next I am binding the GridView with a DataTable object that I created in the Page Load event in the code behind file. To keep things simple I am not connecting any database as it is not the purpose of this tutorial. I created a DataTable object with three columns and filled it with some rows using for loop. The complete code of the Page Load event is shown below:

protected void Page_Load(object sender, EventArgs e)
{
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Salary", typeof(decimal));
for (int i = 1; i < 8; i++)
{
DataRow row = table.NewRow();
row["ID"] = i;
row["Name"] = "Name " + i;
row["Salary"] = 10000 * i;
table.Rows.Add(row);
}
GridView1.DataSource = table;
GridView1.DataBind();
if (GridView1.Rows.Count > 0)
{
GridView1.UseAccessibleHeader = true;
GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;

}
}

By default, The GridView control doesn’t render the <th> tags for the header row which can be an issue for sites where standard compliance and accessibility are important. When we set the property UseAccessibleHeader = true, it replaces the <td> elements of the header row with the correct <th> element. The HeaderRow.TableSection property of GridView control generates <thead> and <tbody> tags to make generated code more accessible. Build and run your project, and you will see the following output.

GridView without Highlighting

Although the above output looks very simple but the important thing to note is the HTML generated by the GridView control. Please check the source code of the page from the browser View Source option and see the HTML table code is generated. Next you need to add following CSS style rules inside the <head> section of the page. We will use the headerRow, highlightRow and selectedRow CSS classes in JQuery code in few minutes.

<style type="text/css">
th
{
text-align:left;
}
.headerRow
{
background-color: #000000;
color:White;
font-weight:bold;
}
.highlightRow
{
background-color: #dadada;
cursor: pointer;
border:solid 1px black;
}
.selectedRow
{
background-color: #808080;
cursor: pointer;
border:solid 1px black;
color:White;
}
</style>

Next add the JQuery script file reference inside the <head> section of the page depending on the script file location and JQuery version you are using.

<script src="scripts/jquery-1.4.3.min.js" type="text/javascript"></script>

Next add the following JQuery code inside a script block in<head>section of the page.

<script type="text/javascript">
$(document).ready(function () {
$('#GridView1 thead').addClass('headerRow');
$('#GridView1 tbody tr').mouseover(function () {
$(this).addClass('highlightRow');
}).mouseout(function () {
$(this).removeClass('highlightRow');
}).click(function () {
$(this).toggleClass('selectedRow');
});

});
</script>

The code defines typical JQuery ready method, which is used to access and manipulate DOM elements when they are loaded by the browser. The first line of code uses a JQuery selector to select<thead>section of the html table and adds a CSS class to the element using JQuery APIaddClass method.

$('#GridView1 thead').addClass('headerRow');

Next I am adding a sequence of three JQuery events mouseover, mouseout and click to the table rows<tr>elements.

$('#GridView1 tbody tr').mouseover(function () {
$(this).addClass('highlightRow');
}).mouseout(function () {
$(this).removeClass('highlightRow');
}).click(function () {
$(this).toggleClass('selectedRow');
});

Each one of these events takes a function handler as a parameter in which you can write code you want to execute when these events occur on table rows. I am using addClass method to add CSS class inside mouseover event handler and removing the same CSS class using theremoveClass method inside mouseout event handler. This will give you hover effect when you will move the mouse on table rows. The clickevent handler uses JQuery API toggleClass method which adds or removes CSS classes based on the class presence. You can read more about these methods at the following URL on JQuery website.
http://api.jquery.com/category/css
If you have followed the complete tutorial with me you will see the GridView with mouseover hover and click effects as shown in the following figure.

GridView with mouseover hover and click effect

I hope you have enjoyed this tutorial as much as I have enjoyed writing it. You can download the full source code of this tutorial by clicking theDownload Source Code button at the top of this page. You can also watch the live demo by clicking the Live Demo button.

Download Source Code

Using JQuery, AJAX, JSON and ASP.NET Web Services

Due to the latest paradigm shift in web development, more and more websites are loading and displaying all types of dynamic contents on the web pages. Web 2.0 based websites such as Gmail. Facebook and Twitter have not only changed the user’s expectations but also forced developers to learn more dynamic and exciting ways to build web applications. Client side web technologies like AJAX, XHTML, DOM, JavaScript and JQuery are now mandatory ingredients of every web developer resume. In my previous tutorial, I have shown you how you can call ASP.NET web services using JQuery AJAX capabilities. In this tutorial, I will show you how you can pass parameters to web services and how you can use JSON data returned from web services to display dynamic contents on web page.

Due to the latest paradigm shift in web development, more and more websites are loading and displaying all types of dynamic contents on the web pages. Web 2.0 based websites such as Gmail. Facebook and Twitter have not only changed the user’s expectations but also forced developers to learn more dynamic and exciting ways to build web applications. Client side web technologies like AJAX, XHTML, DOM, JavaScript and JQuery are now mandatory ingredients of every web developer resume. In my previous tutorial, I have shown you how you can call ASP.NET web services using JQuery AJAX capabilities. In this tutorial, I will show you how you can pass parameters to web services and how you can use JSON data returned from web services to display dynamic contents on web page.

Create a new ASP.NET website in the visual studio and add following Employee.cs class in App_Code folder of your project. I will be using this class from the web service to return the list of Employee class objects to the clients.

public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Salary { get; set; }
}


Next, add an ASP.NET web service EmployeeWebService.asmx in the project by using Add New Item dialog box. The complete web service code is shown below:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class EmployeeWebService : System.Web.Services.WebService {
List<Employee> list = new List<Employee>();
public EmployeeWebService () {
//Uncomment the following line if using designed components
//InitializeComponent();
list.Add(new Employee { Id = 1, Name = "Peter", Salary = 22000 });
list.Add(new Employee { Id = 2, Name = "Mark", Salary = 24000 });
list.Add(new Employee { Id = 3, Name = "James", Salary = 28000 });
list.Add(new Employee { Id = 4, Name = "Simon", Salary = 29000 });
list.Add(new Employee { Id = 5, Name = "David", Salary = 19000 });

}
[WebMethod]
public List<Employee> GetAllEmployees() {
return list;
}

[WebMethod]
public Employee GetEmployeeDetails(string employeeId)
{
int empId = Int32.Parse(employeeId);
Employee emp = list.Single( e => e.Id == empId);
return emp;
}

}

In start, the web service declares a list of Employee objects which I will be using to store employee objects for this tutorial.

List<Employee> list = new List<Employee>();


I have added five employee objects to the list in the constructor of the web service. I am using this approach only for simplifying this tutorial as in a real world application these records are normally stored in the database.

list.Add(new Employee { Id = 1, Name = "Peter", Salary = 22000 });
list.Add(new Employee { Id = 2, Name = "Mark", Salary = 24000 });
list.Add(new Employee { Id = 3, Name = "James", Salary = 28000 });
list.Add(new Employee { Id = 4, Name = "Simon", Salary = 29000 });
list.Add(new Employee { Id = 5, Name = "David", Salary = 19000 });

A web method GetAllEmployees returns the list of employees to the clients.

[WebMethod]
public List GetAllEmployees()
{
return list;
}


Another simple web method GetEmployeeDetails will filter and return a single Employee object based on employee id.

[WebMethod]
public Employee GetEmployeeDetails(string employeeId)
{
int empId = Int32.Parse(employeeId);
Employee emp = list.Single( e => e.Id == empId);
return emp;
}


Next add the following code in your web page in HTML source. It has a DropDownList to display all employees and an HTML table to display single employee details.

<form id="form1" runat="server">
Select Employee:
<asp:DropDownList ID="DropDownList1" runat="server" Width="150">
<asp:ListItem Text="Select" Value="-1" />
</asp:DropDownList>

<br />
<br />
<table style="border: solid 1px black; width: 300px; display: none; background-color: #f3f3f3"
cellpadding="4" cellspacing="0" id="outputTable">
<tr>
<td>Employee ID:</td>
<td><span id="spnEmployeeId" /></td>
</tr>
<tr>
<td>Employee Name:</td>
<td><span id="spnEmployeeName" /></td>
</tr>
<tr>
<td>Salary:</td>
<td><span id="spnSalary" /></td>
</tr>
</table>
</form>

Before staring JQuery AJAX code make sure you have JQuery file available in the scripts folder of your website, and you have added file reference in the page <head> element.
<script src="scripts/jquery-1.4.3.min.js" type="text/javascript"></script>
Next add a JavaScript code block and typical JQuery ready function to get things started when the document is ready and DOM tree is loaded by the browser. The first statement is a call to another JavaScript function GetAllEmployees which is declared just after ready function. This function will call GetAllEmployees web service method, and then it will populate the DropDownList control from the JSON data returned from the web service method. Next the DropDownList change event function handler is defined, which first gets the selected employee id from theDropDownList using JQuery val method and then pass that employee id to another JavaScript function GetEmlployeeDetails which will retrieve details of that particular employee by calling web service GetEmployeeDetails method and then will display details in HTML table.

<script type="text/javascript">
$(document).ready(function () {
// Load Employees
GetAllEmployees();
var DropDownList1 = $("#DropDownList1");
DropDownList1.change(function (e) {
var employeeId = DropDownList1.val();
if (employeeId != -1) {
// Get Employee Details
GetEmployeeDetails(employeeId);
} else {
$("#outputTable").hide();
}
});
});
function GetAllEmployees() {
// JQuery AJAX Code Here
}
function GetEmployeeDetails(employeeId) {
// JQuery AJAX Code Here
}

</script>


As you can see in the above code, I didn’t define the GetAllEmployees and GetEmployeeDetails functions so that you can focus on ready function implementation and can understand more easily what is going on in JQuery ready function. To complete this tutorial, I need to show you the code required inside the above two functions to call web services methods and to update controls and user interface elements. Following is the implementation of GetAllEmployees function:

function GetAllEmployees()
{
var DropDownList1 = $("#DropDownList1");
$.ajax({
type: "POST",
url: "EmployeeWebService.asmx/GetAllEmployees",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var Employees = response.d;
$.each(Employees, function (index, employee) {
DropDownList1.append('<option value="' + employee.Id + '">' + employee.Name + '</option>');
});

},
failure: function (msg) {
alert(msg);
}
});
}


In the above code snippet, JQuery ajax() method is used to send AJAX request to ASP.NET web service method GetAllEmployees. From the parameters, you can easily guess the service method url, request type (POST) and data type (JSON). If you are not familiar with the ajax()method parameters, I will recommend you to read my tutorial Calling ASP.NET Web Services using JQuery AJAX for more detailed understanding of the ajax() method and JSON.
Inside the success function handler of ajax() method, I have used JQuery each() method to loop through all the employees I received in JSON response (response.d) and I appended the HTML elements inside DropDownList to display all employees. If you will build and test your page in the browser you will see DropDownList populate with employee names as shown in the following figure. You can also see the JSON response inFireBug just below to the DropDownList.

JQuery AJAX JSON Response

The following is the code required for the GetEmployeeDetails function. The code is almost similar to the GetAllEmployees function as it is also using JQuery ajax() method to call web service method but there are two differences. First, I am passing employee id as a parameter in JSON format using the data option of JQuery ajax() method. Second, inside success method I am not using any loop to iterate employees as there is only one employee to receive from the web service method. Note the Employee class properties Id, Name and Salary are used to display values inside span elements declared in HTML table above.

function GetEmployeeDetails(employeeId)
{
$.ajax({
type: "POST",
url: "EmployeeWebService.asmx/GetEmployeeDetails",
data: "{'employeeId':'" + employeeId + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response)
{
var Employee = response.d;
$("#spnEmployeeId").html(Employee.Id);
$("#spnEmployeeName").html(Employee.Name);
$("#spnSalary").html(Employee.Salary);
$("#outputTable").show();

},
failure: function (msg)
{
alert(msg);
}
});
}

That’s all we need to call web service methods using JQuery AJAX and to display single or multiple records coming from web service method in JSON format. Build and run your web page, and you will see output similar to following figure:

JQuery AJAX JSON Response

 

Download Source Code Download Source Code Live Demo Live Demo

Select Deselect GridView Rows using a Checkbox in JQuery

Many websites require functionality for letting their site visitors to select and deselect all the rows in GridView using a single checkbox normally available in the header row. You may have seen the examples of such functionality in Yahoo Mail or Hotmail inbox where you can select all the emails by clicking the single Checkbox on top of the email's grid. In this tutorial, I will show you how you can provide this functionality in ASP.NET GridView control using few lines of JQuery code.

Select Unselect GridView Rows

To get started, create an ASP.NET website and drag a GridView control on the page. For this tutorial, I am using ID, Name and Salary columns, so I added three bound fields and one TemplateField that will contain the checkboxes in the header as well as in the individual row. Following is the complete HTML source for the GridView control.

<asp:GridView ID="GridView1" runat="server" Font-Size="10pt"
Font-Names="Verdana" CellPadding="4" Width="400px" GridLines="None"
ForeColor="#333333" AutoGenerateColumns="false">
<RowStyle BackColor="#EFF3FB" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkHeader" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkRow" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ID" HeaderText="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Salary" HeaderText="Salary" />
</Columns>
</asp:GridView>

To keep this tutorial simple, I am not connecting my GridView with the database and showing some sample data in the GridView. Add the following code in the Page Load event of the page to add few rows of data.

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadData();
}
}
private void LoadData()
{
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Salary", typeof(decimal));
for (int i = 1; i < 8; i++)
{
DataRow row = table.NewRow();
row["ID"] = i;
row["Name"] = "Name " + i;
row["Salary"] = 10000 * i;
table.Rows.Add(row);
}
GridView1.DataSource = table;
GridView1.DataBind();
}


Now we need only few lines of JQuery code to provide the functionality of selecting or deselecting rows using the checkbox added in the header of the GridView. Add the JQuery script file reference in the head element of the page.

<script src="scripts/jquery-1.4.3.min.js" type="text/javascript"></script>
Add the following JavaScript block inside the head element of the page.
<script type="text/javascript">
$(document).ready(function() {
var headerCheckbox = $('#GridView1 > tbody > tr > th > input:checkbox');
headerCheckbox.click(function() {
var headerChecked = $(this).attr('checked');
var rowCheckboxes = $('#GridView1 > tbody > tr > td > input:checkbox');
rowCheckboxes.attr('checked', headerChecked);
});

});
</script>


The above code is using typical JQuery ready function to add some JQuery statements or code. The first line access the checkbox available in the header row of the GridView using JQuery selector.
var headerCheckbox = $('#GridView1 > tbody > tr > th > input:checkbox');
Once we have the reference of header checkbox, we are using the click event function handler that will allow us to run some code every time user will click the header checkbox. Inside click event function handler, the first line stores the current state of the header checkbox in aheaderChecked variable. The second line gets the reference of all the checkboxes in all the rows in GridView and then set their state to the same state as the header checkbox using JQuery attr function.

headerCheckbox.click(function() {
var headerChecked = $(this).attr('checked');
var rowCheckboxes = $('#GridView1 > tbody > tr > td > input:checkbox');
rowCheckboxes.attr('checked', headerChecked);
});


Build and test your web page and click the checkbox in the header row, and you will be able to select or deselect all checkboxes in GridView rows. You can click the Live Demo button to see the working example of this tutorial.

Download Source Code Download Source Code Live Demo Live Demo

Saving images in database using ASP.NET FileUpload Control

Saving and displaying images in database tables is a common requirement in ASP.NET projects. There are two ways to store images in database either you store image URLs in database as normal string or you store image as binary data. In this tutorial I will show you how you can upload and save images directly in SQL Server database table as binary data.

For this tutorial I have created a table in SQL Server database called Products with three columns, ID, ProductName and ProductImage as shown in the figure below. Note the data type of ProductImage column is varbinary not image. This is because image data type will be removed in future versions of SQL Server database so avoid using image data type.

Sample Table to Store Images

Now let’s take a look at the form I am going to use, to upload images to the above table.

<form id="form1" runat="server">
Product Name:
<asp:TextBox id="txtProductName" runat="server" />
<br />
Product Image:
<asp:FileUpload id="FileUpload1" runat="server" />
<asp:Button id="btnSave" runat="server" Text="Save Product" onclick="btnSave_Click" />
<br /><br />
<asp:Label id="lblMessage" runat="server" />
</form>


The above code looks pretty straightforward as it is just showing one TextBox, one ASP.NET 2.0 FileUpload control and a Button to Save Product Name and Image in database as shown in the following figure:

Following is the C# code for Save Product button click event.

protected void btnSave_Click(object sender, EventArgs e)
{
if(FileUpload1.HasFile)
{
string productName = txtProductName.Text;
byte[] productImage = FileUpload1.FileBytes;
string constr = "Server=TestServer; Database=SampleDB; uid=sa; pwd=abc123";
string query = "INSERT INTO Products(ProductName, ProductImage) VALUES(@ProductName, @ProductImage)";
SqlConnection con = new SqlConnection(constr);
SqlCommand com = new SqlCommand(query, con);
com.Parameters.Add("@ProductName", SqlDbType.NVarChar).Value = productName;
com.Parameters.Add("@ProductImage", SqlDbType.VarBinary).Value = productImage;
con.Open();
int result = com.ExecuteNonQuery();
con.Close();
if (result > 0)
{
lblMessage.Text = "Product Saved Successfully";
}
}
else
{
lblMessage.Text = "Please Select Product Image File";
}
}


The above code is running simple SQL Insert query to store images in database table. FileUpload control HasFile property checks whether user has selected a file or not. FileBytes property returns the image file as the array of bytes.
If you want to upload the image file to a File System then you can also use FileUpload SaveAs method that requires the server path to upload the file. If you want to verify the file size and its type then you can use FileUpload.PostedFile.ContentLength andFileUpload.PostedFile.ContentType properties.

Export ASP.NET GridView to Excel

Many developers use GridView control to display web reports in their ASP.NET websites. GridView control render data in a tabular form just like HTML tables but it lack the functionality of exporting its contents to any other format such as Excel of PDF file. It is very common requirements of many clients to export web report data to Excel file so that they can perform some analysis using Excel built in features. In this Tutorial I will show you how to export GridView control as Excel File.

For the purpose of this tutorial, I setup a sample ASP.NET page showing products from Northwind database using GridView control. I hope the data binding code will not be new for you if you have already read some of the articles related to GridView control on my website. Following is the preview of the page I am going to use to export to excel.

Export to Excel Page

Following Code shows how you can bind data to GridView control in the Page_Load event. Please keep in mind that for brevity I am storing connection string in the code. You should always store your database connection strings in web.config.

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


As you can guess from the above screen shot that the button “Export to Excel” will implement the main export functionality. The code below is the button click event handler code to export GridView control contents to excel but you can use similar code to export to other formats by changing the ContentType property.

Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=Products.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
GridView1.RenderControl(htmlWriter);
Response.Write(stringWriter.ToString());
Response.End();


Sometimes, when you render any asp.net control dynamically as I am doing with the GridView control in this tutorial, you can get HttpExceptionwith the following message:
Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.
The problem can be solved by overriding Page class VerifyRenderingInServerForm method which confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time.

public override void VerifyRenderingInServerForm(Control control)
{ }


When you will click the Export to Excel button you will see the following dialog box asking you to open or save dynamically generated Excel file.

Open/Save Excel File Dialog Box

Following screen shot shows you how the data is saved in Excel file.

export_to_excel_preview.JPG

Handling Errors and Exceptions in ASP.NET

No matter how experience developer you are and how perfect code you write, sooner or later your code will be interrupted by a programming mistake, some invalid user input, wrong data or any other unexpected circumstances. No software can run free from error, and ASP.NET applications are no exception. In this tutorial, I will show you how you can do error handling in ASP.NET applications and how you can configure custom error pages with user friendly messages.

Errors can occur in a variety of situations in your ASP.NET web applications. Some of the most common errors include attempt to access an object which is not initialized or attempt to connect a file which does not exist and so on. When an error occurs in your code, .NET checks to see whether any error hander appears in the current scope. If there is no error handler available, the page processing aborted and depending on whether the request is from the local computer or a remote client, an error page is displayed in the browser. Following is a sample error page showing user that an attempt to divide by zero has been made on the page which caused an error.

ASP.NET Error Page

A rich ASP.NET error page

Although the above error page is quite useful for developer to diagnose the actual cause of the error but it is not the page you want your end users to see in any situation because it can not only annoy them but it can also make them feel that the application is unstable or poorly developed. If an ASP.NET application is carefully developed and configured, the above error page will never appear.
Exception Handling
Exception handling is a programming technique which is supported by most modern languages and that allows developers to react to problems that occur at run time due to factors outside their control. When an exception occurs in your ASP.NET application code, you can handle it in a number of ways. The most common approach is to use structured exception handling in which you can use try-catch code blocks around error-prone code to catch specific exceptions that you can deal with, such as System.IO.FileNotFoundException. Following is the typical structure of try-catch blocks.

try
{
// Problematic code goes here (i.e. opening a file, connecting to a database).
}
catch
{
// An error has been detected. You can deal with it here.
}
finally
{
// Clean up code here, regardless of whether or not there is an error
}


The try statement normally contains the code which can cause errors in your application. Any exceptions occur in the try block can be caught automatically and the code in the catch block will be executed when the error is detected. Usually, the catch block is used to report the error to the user or log it for future reference. Following code snippet shows a typical example of try-catch code block.

try
{
// Risky code to connect database goes here.
}
catch (SqlException ex)
{
// Catches common problems like connection errors.
}


Structure exception handling is very flexible because it allows you catch multiple specific exceptions as shown below:

try
{
// Risky code to connect database goes here.
}
catch (SqlException ex)
{
// Catches common problems like connection errors.
}
catch (NullReferenceException ex)
{
// Catches problems resulting from an uninitialized object.
}
catch (Exception ex)
{
// Catches any other errors.
}


In .NET all exception classes are derived from the base Exception class so that last catch block in the above code snippet will catch any type of exception occur in the try block.
Handling Exceptions at Page Level
If you have so many exception handling code blocks in your page, you can consider using the page-level error handler to catch multiple specific exceptions that might happen anywhere on the page. To handle exceptions at a page level, override the OnError method in your page and callServer.GetLastError() method which will give you access to the exception that just occurred. The following code snippet shows the usage ofOnError method:

protected override void OnError(EventArgs e)
{
Exception ex = Server.GetLastError();
if (ex.GetBaseException() is DivideByZeroException)
{
Response.Write("Divide By Zero Error Occurred!");
Response.StatusCode = 200;
Server.ClearError();
Response.End();
}
}


Handling Exceptions at Application Level
ASP.NET allows you to catch all the unhandled exceptions of your application in a centralized location in Global.asax file. The following code shows how you can implement this behavior using the Application_Error method in Global.asax file.

void Application_Error(object sender, EventArgs e)
{
Exception ex = Server.GetLastError();
if (ex.GetBaseException() is DivideByZeroException)
{
System.Diagnostics.Trace.WriteLine(ex.ToString());
Server.ClearError();
}
}

Error Pages
If you are creating ASP.NET applications from some time, you must become familiar with the rich error pages that are shown to describe unhandled errors in your web pages. These rich error pages are extremely useful for developers for diagnosing the problems in their code during the development as they contain a wealth of information. Sometime these pages also display the source code where the problem occurred with the error line highlighted. These pages also display the type of error and a detailed error message describing the problem. The sample of such rich error page is shown at the start of this tutorial above.
By default, this rich error page is shown only for local requests that are sent from the http://localhost domain. ASP.NET doesn’t show rich error pages for requests from other computers; rather they receive a generic error page shown below.

Generic Client Error Page

A generic ASP.NET error page

This generic page does not have any details about the type of error or the code as sharing this information with other users would be a security risk. This page includes a generic message explaining that an error has occurred and describing how to change the configuration settings. You can change the configuration of your web application so that all users see the rich ASP.NET error page or user friendly custom error page. To configure these settings, you need to add the section in the web.config file as shown below:

<configuration>
<system.web>
<customErrors mode="RemoteOnly" />

</system.web> …
</configuration>


The mode attribute value can be one of the following:
RemoteOnly: The local requests made from the current computer will get rich error pages with detailed error information including its type, stack trace and error messages. The remote users will see generic error page as shown n the above figure. This is default value for mode attribute.
Off: Both local and remote users will see rich error pages with detail information about the error including error type, stack trace and error messages. This setting is helpful during development but should not be used in a deployed ASP.NET application.
On: Generic error pages are shown to both local and remote users. This is secure option but it complicates debugging during development because the developer will not be able to see the stack trace or error messages.
When you are deploying an ASP.NET application on a production server, you should use either RemoteOnly or On value for the mode attribute. However you don’t want your end users to see either rich or generic error pages as they are not very useful for them. In such cases, you can implement custom error pages in your application. You can create a single generic error page and configure ASP.NET to use it by addingdefaultRedirect attribute in section in web.config as shown below:

<configuration>
<system.web>
<customErrors mode="RemoteOnly" defaultRedirect="~/error.aspx" />

</system.web>

</configuration>


Now, if there is any HTTP error or unhandled application error occurs in your application, the user will be forwarded to error.aspx page. Please keep in mind that if you will set the value of mode attribute to Off, the user will still see the ASP.NET error page instead of error.aspx. In scenarios where you have set the value of mode attribute to RemoteOnly, remote users will see error.aspx while the local users see the ASP.NET error page. Following figure is showing a user friendly error.aspx page which all web site users will see if there is any error in the application.

Custom Error Page

A custom user friendly error page

You can do even more fine tuning of your web application by targeting specific HTTP errors to different error pages. This technique is shown in the following code:

<configuration>
<system.web>
<customErrors mode="RemoteOnly" defaultRedirect="~/error.aspx">
<error statusCode="403" redirect="403.aspx" />
<error statusCode="404" redirect="404.aspx" />

</customErrors>
</system.web>
</configuration>


Sometimes, the difference between an ordinary website and a professional web application is how it deals with errors.

Source:ezzylearning

Connection String Encryption in Web.config using C#

Almost all ASP.NET web sites connect database and one of the best practices in ASP.NET is to store your database connection string outside your source code typically in web configuration file (web.config). This gives you benefit of changing your database related information such as the server name, user id or password without any modification or compilation of your source code. To provide additional security of important connection string information you should always encrypt your connection string in web.config file.

ASP.NET 2.0 allow you to encrypt and decrypt your connection string in web.config. In the following tutorial, I will show you how you can encrypt and decrypt connection strings in C# using .NET Framework built in classes available in System.Configuration and System.Web.Configuration namespaces.

To test the following code you should have your connection string in web.config file as following code shows:

<configuration>
<connectionStrings>
<add name="MyConnectionString"
connectionString="Server=TestServer; Database=TestDB; UID=test; PWD=test"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>

Here is the C# code to encrypt and decrypt connection string. Make sure you have reference of System.Configuration and System.Web.Configuration available to test this code.
Encryption

try
{
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
ConfigurationSection section = config.GetSection("connectionStrings");
if (!section.SectionInformation.IsProtected)
{
section.SectionInformation.ProtectSection("RSAProtectedConfigurationProvider");
config.Save();
}
}
catch (Exception ex)
{ }

Decryption

try
{
Configuration config = WebConfigurationManager.OpenWebConfiguration("~");
ConfigurationSection section = config.GetSection("connectionStrings");
if (section.SectionInformation.IsProtected)
{
section.SectionInformation.UnprotectSection();
config.Save();
}
}
catch (Exception ex)
{ }

Download Source Code Download Source Code

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;
}

Calling Web Services in Client Script using ASP.NET AJAX

Web Services play an important role in data transport and communication between the client the server. Web services reside on the server and wait to be called by any client and most of the time these clients are written in server side technologies such as ASP.NET, PHP or JSP etc. ASP.NET AJAX provides web developers ability to call web services from the client side language such as JavaScript asynchronously to improve the user experience and to avoid full page refresh and postback. In this tutorial, I will show you how you can call an ASP.NET web service with the help of ASP.NET AJAX.

For the purpose of this tutorial I have created a web service with the name ProductsService.asmx. If you are new to web services and don’t know how to add web service right click on your website name in Solution Explorer and click Add New Item option and select the Web Service icon from the available file templates as shown in figure below. A new file with the name ProductsService.asmx will be added in your website and the code behind file for the web service will be added in App_Code folder.

Add ASP.NET Web Service

Notice the ProductsService class is derived from the System.Web.Services.WebService class available in .NET Framework class library. Also check the following directive in your code and make sure it is not commented because this directive is required to call web service using ASP.NET AJAX.[System.Web.Script.Services.ScriptService]
The implementation of web service is fairly straight forward. It has only one method GetProducts which is decorated with [WebMethod] attribute that is required to expose web service methods to consumers and calling applications. The method takes category id as a parameter and return some products based on the category. I am returning hard coded products names and not connecting database in this tutorial but you can easily write code to return products from the database.

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

[System.Web.Script.Services.ScriptService]
public class ProductsService : System.Web.Services.WebService
{
[WebMethod]
public List<string> GetProducts(int categoryId)
{
List<string> list = new List<string>();
if (categoryId == 1)
{
list.Add("Nokia N95");
list.Add("Nokia N70");
list.Add("Nokia 6630");
}
else
{
list.Add("Dell Laptop");
list.Add("HP Laptop");
list.Add("Sony Laptop");
}
return list;
}
}


To consume web service by using client script you need to add an instance of the ASP.NET AJAX ScriptManager control in your page. This control supports a Services collection which can be used to add the reference of web services you want to call from client side JavaScript. The ASP.NET AJAX asynchronous communication layer automatically generates JavaScript proxy classes for each Web service reference you add usingScriptManager control.
Once your page is requested, the proxy class is downloaded to the browser at the page load time and provides a client object that represents the exposed methods of a Web service. To call a method of the Web service, you can call corresponding method of generated proxy class. The proxy class in turn communicates with the Web service asynchronously by using XmlHttpObject of the browser.
For this tutorial, I have added the reference of ProductsService.asmx by using <asp:ScriptReference> element inside Services collection under the <asp:ScriptManager> element. The remaining form has a DropDownList, an HTML button and a Label control. Notice that the onclick event of the Button1 control is calling a JavaScript function Button1_onclick() which needs to be defined in the JavaScript in your page.

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/ProductsService.asmx" />
</Services>
</asp:ScriptManager>

Select Category:
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Value="1">Mobiles</asp:ListItem>
<asp:ListItem Value="2">Laptops</asp:ListItem>
</asp:DropDownList>
<input id="Button1" type="button" value="Get Products"
onclick="Button1_onclick()" />
<br />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
</form>


As I mentioned earlier that calling a Web service method from client script is asynchronous means the communication will take place behind the scene and user will remain interactive with the page. If your web service returns some data you must provide a callback function you want to execute on successful call to web service. You can also provide another callback function to handle errors in case the Web service call failed due to any communication or server error or Web service return no data.
I have added the following JavaScript code in my page to call Web service. Notice how I have called the GetProducts method of the Web service using the ProductsService proxy class generated automatically for me when I have added the Web service reference using ScriptManagercontrol. Also notice the callback functions onSuccess and onFailed have been passed as a second and third parameter in the proxy class GetProducts method to receive the results or error messages returned by the Web service and to update the page accordingly.

<head runat="server">
<title>Consuming Web Services From AJAX</title>
<script type="text/javascript">
function Button1_onclick()
{
var categoryId = $get("DropDownList1").value;
ProductsService.GetProducts(categoryId, onSuccess, onFailed);
}
function onSuccess(result)
{
var Label1 = $get("Label1");
Label1.innerHTML = "";
for(i=0 ; i<result.length ; i++)
{
Label1.innerHTML += result[i] + "<br />";
}
}
function onFailed(error)
{
var Label1 = $get("Label1");
Label1.innerHTML = "Service Error: " + error.get_message();
}
</script>
</head>


Build your project and test your page in the browser and you will see output similar to the following when you will click the button after selecting a category from the DropDownList.

ASP.NET AJAX Web Service

Display Photos in ASP.NET using Flickr.NET API

One of the most common ingredients of any successful website is to display photos to the site visitors along with photos and their metadata search facility. There are number of photo sharing web sites and services providing the large number of photos for websites and blogs. The most popular and commonly used site is Flickr.com, which provides very flexible and powerful API to web developers and exposes almost all the data stored on the site to offer web developers limitless possibilities for creating mashups, widgets, etc. Due to the popularity of Flickr API, many client libraries are available for almost all programming languages such as .NET, Java or PHP. These libraries make development with Flickr API even easier by hiding lower level API details and also allows you to work with your favorite programming language and environment. In this tutorial, I will show you how you can use one such library Flickr.NET to search and display photos using C# and ASP.NET.
Using Flickr.NET API in ASP.NET
Before I start this tutorial, please keep in mind that the developer key and shared secret is required to make requests to the Flickr API so make sure you have got your developer key and shared secret from the Flckr website at the following URL.
http://www.flickr.com/services/api
You also make sure that you have downloaded the latest version of Flickr.NET API from codeplex website.
http://flickrnet.codeplex.com
To get started, create a new ASP.NET website in Visual Studio and add the reference of FlickrNet.dll you just downloaded from codeplex. To create an interface shown in the above figure, you need to add a table with three rows and two columns. Inside that table, you need to add search textbox, go button, some labels and a DataList control to show thumbnails. Following is the complete markup of the page used in this tutorial.
<div style="text-align: center">
<center>
<table cellpadding="5" cellspacing="0" style="border: 2px solid #0066CC; width: 60%;">
<tr>
<td style="width: 40%;">
Search:
<asp:TextBox ID="SearchTextBox" runat="server"></asp:TextBox>
<asp:Button ID="GoButton" runat="server" Text="GO"
OnClick="GoButton_Click" />
</td>
<td style="vertical-align: top">
<asp:Label ID="PhotoDateTaken" runat="server"></asp:Label>
</td>
</tr>
<tr>
<td style="vertical-align: top">
<asp:DataList ID="ThumbnailsList" runat="server" HorizontalAlign="Center"
RepeatColumns="3" Width="100%"
OnSelectedIndexChanged="ThumbnailsList_SelectedIndexChanged">
<ItemStyle HorizontalAlign="Center" />
<ItemTemplate>
<asp:ImageButton ID="ThumbnailImage" runat="server"
ImageUrl='<%# Eval("SquareThumbnailUrl") %>'
AlternateText='<%# Eval("Title") %>'
ToolTip='<%# Eval("Title") %>
'
CommandName="Select">
</asp:ImageButton>
<asp:Literal ID="HiddenPhotoId" runat="server"
Text='<%# Eval("PhotoId") %>' Visible="false" />
<asp:Literal ID="HiddenPhotoUrl" runat="server"
Text='<%# Eval("MediumUrl") %>' Visible="false" />
</ItemTemplate>
</asp:DataList>
</td>
<td style="vertical-align: top">
<asp:Image ID="PreviewImage" runat="server" />
</td>
</tr>
<tr>
<td style="vertical-align: top">&nbsp;</td>
<td style="vertical-align: top">
<asp:Label ID="PhotoDescription" runat="server"></asp:Label>
</td>
</tr>
</table>
</center>
</div>
The DataList control used in the above markup is using an ImageButton control to display image thumbnails inside the ItemTemplate. Notice how the ImageUrl property of the ImageButton is bound with SquareThumbnailUrl property of the Flickr.NET API Photo class. Furthermore, notice the AlternateText and ToolTip properties are bound with Title property. I also used two hidden literal controls to store PhotoId and itsMediumUrl properties, which will be used to display photo preview and to get more details like its description or date the photo is taken from Flickr website.
It is now time to show you the Flickr.NET API in action by moving to the page code behind file. Declare the following two variables on top of the class and store your developer key and shared secret in them.
string flickrKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
string sharedSecret = "xxxxxxxxxxxxxxx";
Define the following GetPhotos method to search photos from Flickr website using Flickr.NET API and to bind the DataList with the photos returned from Flickr. This method will be called in Page Load event with default keyword and then from Go button click with the keyword user will specify in the search textbox.
private void GetPhotos(string tag)
{
PhotoSearchOptions options = new PhotoSearchOptions();
options.PerPage = 12;
options.Page = 1;
options.SortOrder = PhotoSearchSortOrder.DatePostedDescending;
options.MediaType = MediaType.Photos;
options.Extras = PhotoSearchExtras.All;
options.Tags = tag;
Flickr flickr = new Flickr(flickrKey, sharedSecret);
PhotoCollection photos = flickr.PhotosSearch(options);

ThumbnailsList.DataSource = photos;
ThumbnailsList.DataBind();
}
The method GetPhotos first declares an object of PhotoSearchOptions class that allows us to set all the search related parameters in a single place. You can set how many photos you want to retrieve per page along with the current page index. You can set the sort order, media type (photos, videos etc.) to fetch from Flickr website. You need to set the Tags property with any string value you want to search. Flickr.NET API also exposes Flickr class that have PhotoSearch method to actually search photos from Flickr. It takes PhotoSearchOptions object as parameter and returns PhotoCollection returned by using the search options specified. Finally, I bind the photos collection with the DataList control on the page. Similar to the above method is the GetDescription method which takes photoId as parameter and returns Photo description and other useful information from Flickr website.
private void GetDescription(string photoId)
{
Flickr flickr = new Flickr(flickrKey, sharedSecret);
PhotoInfo info = flickr.PhotosGetInfo(photoId);

PhotoDescription.Text = info.Description;
PhotoDateTaken.Text = info.DateTaken.ToString("MMMM dd, yyyy");
}
Call the above methods in the Page Load event as shown in the code below. Notice how I am getting hidden photoId and photoUrl from the first Item shown in the DataList to make sure user see the first image preview and its description when the page loads first time.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string defaultKeyword = "nature";
SearchTextBox.Text = defaultKeyword;
GetPhotos(defaultKeyword);
Literal HiddenPhotoId =
ThumbnailsList.Items[0].FindControl("HiddenPhotoId") as Literal;
Literal HiddenPhotoUrl =
ThumbnailsList.Items[0].FindControl("HiddenPhotoUrl") as Literal;
string photoId = HiddenPhotoId.Text;
string photoUrl = HiddenPhotoUrl.Text;
PreviewImage.ImageUrl = photoUrl;
GetDescription(photoId);
}
}
The same GetPhotos method will be called from the Go button click event to search photos with the user given keyword.
protected void GoButton_Click(object sender, EventArgs e)
{
string keyword = SearchTextBox.Text.Trim();
GetPhotos(keyword);
}
Finally, I am using SelectedIndexChange event of the DataList control to allow user to select any photo by clicking the thumbnail and showing the user selected photo preview and description on the right hand side of the thumbnails.
protected void ThumbnailsList_SelectedIndexChanged(object sender, EventArgs e)
{
Literal HiddenPhotoId =
ThumbnailsList.SelectedItem.FindControl("HiddenPhotoId") as Literal;
Literal HiddenPhotoUrl =
ThumbnailsList.SelectedItem.FindControl("HiddenPhotoUrl") as Literal;
string photoId = HiddenPhotoId.Text;
string photoUrl = HiddenPhotoUrl.Text;
PreviewImage.ImageUrl = photoUrl;
GetDescription(photoId);
}
Download Source Code

Using ASP.NET ImageMap Control

Many web designers try to impress their website visitors with animated flash buttons or crazy JavaScript navigation menus, but they forget the old HTML Image maps. Image maps are images with clickable areas called hotspots, which allow a user to navigate to another page or website. Following the same old HTML concept of image maps, Microsoft introduced the server side ImageMap control for ASP.NET developers that let you convert any image into a navigation menu by just setting few properties. In this tutorial, I will show you how to use ASP.NET server side ImageMap control with Rectangular, Circular or even free form Polygon style hotspots.

Before you start this tutorial, you need to make sure that you have an image ready which you want to use as ImageMap. It can be a toolbar image created in any graphic tool such as Photoshop, or it can be a map of your or home or country. I have created the following image, especially for this tutorial to show you all types of hotspots ASP.NET ImageMap control supports. You can save this image on your desktop and use it for playing with ASP.NET ImageMap control.

ASP.NET ImageMap Control

To get started, create an ASP.NET website project in Visual Studio and add the image in your project root or images sub directory. Next, drag theImageMap control on the page from the left hand side toolbox. Set the ImageUrl property of the control and you will be able to see your image appear on the designer area of the page. If you see the properties of this control in the properties window, you will notice that all the basic properties like BackColor, BorderColor, etc. are available along with ImageAlign and AlternateText properties to fine tune your image look and feel on the page. The properties which need more explanations are HotSpotMode and HotSpots.
HotSpotMode property let you specify the default click behavior of the hotspot inside the ImageMap control. It can be set to one of the followings:
Inactive: This value means that HotSpots does not have any behavior so nothing will happen if the user will click on image.
Navigate: This value allows you to navigate user to any URL.
PostBack: This property allows you to generate post back behavior on user clicks and very useful if you want to execute code on the server side based on the user clicks.
NotSet: This property checks the behavior set by the HotSpotMode property and if none of the above three values are set then all HotSpots navigate to a URL.
Next you need to define the hotspots to divide your image into clickable areas. If you will click the ellipse next to the HotSpots property in the properties window you will see the following HotSpot Collection Editor dialog appear on the screen that lets you specify different types of hotspots. You can add Rectangle, Circle or Polygon hotspots to your image depending upon your image and requirement.

ASP.NET ImageMap Controls Hotspots

All these hotspots types have some properties to customize the hotspot region and behavior. You can specify Left, Top, Right and Bottom for Rectangle hotspot and X, Y and Radius properties for Circle hotspot. The Polygon hotspot requires a serious of X and Y coordinates to create a free form hotspot. All these hotspots types also have HotSpotMode property available to specify their click behavior individually so you can have one hotspot that navigates the user to another page and other hotspot which generate postback to the server and yet another hotspot which does nothing when user click on it. You also have PostBackValue property to send different values to the server on postback. You also haveTarget property to open the URL in a new window if you want and other basic properties such as NavigateUrl to specify the URL to navigate to on user click and AlternateText that will show a nice tool tip when the user will move the mouse over that particular hotspot.
In the sample image I used in this tutorial, the facebook and twitter logos will use navigate behavior while the other four will generate postback to the server. The facebook and twitter logos will use Rectangle hotspots, Wordpress, BMW and Windows logos will use Circle hotspots and the star will show you how to use Polygon hotspot. Following is the complete HTML markup used in this tutorial.

<asp:ImageMap ID="ImageMap1" runat="server" ImageUrl="~/images/aspnet_imagemap.jpg"
OnClick="ImageMap1_Click">
<asp:RectangleHotSpot AlternateText="Facebook" Bottom="62"
HotSpotMode="Navigate" Left="14" NavigateUrl="http://www.facebook.com"
Right="152" Target="_blank" Top="11" />
<asp:RectangleHotSpot AlternateText="Twitter" Bottom="61"
HotSpotMode="Navigate" Left="156" NavigateUrl="http://www.twitter.com"
Right="306" Target="_blank" Top="11" />
<asp:CircleHotSpot AlternateText="WordPress" HotSpotMode="PostBack"
PostBackValue="WordPress" Radius="41" X="50" Y="118" />
<asp:CircleHotSpot AlternateText="BMW" HotSpotMode="PostBack"
PostBackValue="BMW" Radius="41" X="155" Y="121" />
<asp:CircleHotSpot AlternateText="Windows" HotSpotMode="PostBack"
PostBackValue="Windows" Radius="44" X="266" Y="122" />
<asp:PolygonHotSpot AlternateText="Star" HotSpotMode="PostBack"
PostBackValue="Star" Coordinates="108,217, 141,210, 157,181, 173,210, 207,217, 184,242, 188,276, 158,261, 127,275, 131,243" />
</asp:ImageMap>
<br />
<asp:Label ID="Label1" runat="server" Width="322px" BackColor="#FFFFCC" BorderColor="Black"
BorderStyle="Solid" BorderWidth="1px"></asp:Label>

Note, I have also added a Label control at the bottom that will be used to display hotspots PostBackValue on user clicks. The ImageMap control supports click event that allows you to capture the user clicks on different hotspot areas in a single place. It gets the ImageMapEventArgs type object as one of its argument that has PostBackValue property which you can use in the server side code on postback. The following code shows the ImageMap click event handler used in this tutorial.

protected void ImageMap1_Click(object sender, ImageMapEventArgs e)
{
Label1.Text = e.PostBackValue.ToString();
}

Now, It’s the time to test our ImageMap control in the browser, press F5 and try to click different logo hotspots and you will see the Label control showing you the PostBackValue as you will click the logo that has PostBack behavior defined.

ASP.NET Image Map with Postback

SourceCode             Demo