
Read more »





Image upload and previewing is a very basic requirement usually when we come across user registration page or add and edit an institution, etc. In this post I am providing here the sample which does the same using ASP.NET Ajax.
I had given here just a simple example just to upload and preview the image, I am not going to save the image in the Database or Load from the Database, but of course you can extend this control based on your requirements.
This is how the final screen will look once you complete the code:
You will need Ajax Control Toolkit for AsyncFileUpload control, this controls helps to perform the asynchronous operation without page refresh. Best way to get this through NuGet package manager in you project.
Now lets see the ASP.NET Page and the Code Behind for that.
1: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="UploadImage.aspx.cs" Inherits="UploadImage" %>
2: 3: <%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="ajaxToolkit" %>
4: 5: 6: <!DOCTYPE html>
7: 8: <html xmlns="http://www.w3.org/1999/xhtml">
9: <head runat="server">
10: <title></title>
11: 12: <script language="javascript" type="text/javascript">1:2: function getRandomNumber() {3: var randomnumber = Math.random(10000);4: return randomnumber;5: }6:7: function OnClientAsyncFileUploadComplete(sender, args) {8: var handlerPage = '<%= Page.ResolveClientUrl("~/ImageRequestHandler.ashx")%>';9: var queryString = '?randomno=' + getRandomNumber() + '&action=preview';10: var src = handlerPage + queryString;11: var clientId = '<%=previewImage.ClientID %>';12: document.getElementById(clientId).setAttribute("src", src);13: }14:</script>
13: 14: </head>
15: <body>
16: <form id="form1" runat="server">
17: <ajaxToolkit:ToolkitScriptManager ID="toolKitScriptManager" runat="server">
18: </ajaxToolkit:ToolkitScriptManager>
19: <div>
20: <asp:Panel ID="pFileUpload" runat="server">
21: <label>
22: Image Source:</label>
23: <ajaxToolkit:AsyncFileUpload ID="asyncFileUpload" runat="server"
24: OnClientUploadComplete="OnClientAsyncFileUploadComplete"
25: OnUploadedComplete="OnAsyncFileUploadComplete" Width="374px" />
26: <br />
27: <asp:Image runat="server" ID="previewImage" Width="150px" BorderStyle="Double" BorderColor="Green" />
28: </asp:Panel>
29: </div>
30: </form>
31: </body>
32: </html>
The code above is very simple and self explanatory, still let me quickly give you a walkthrough. In the Script section of this page I am writing an function which gets called by the AsyncFileUpload control once the file upload to server is completed. Basically in Server side we are just saving the image temporarily in Session which is referenced in Handler section which I am going to cover very soon. In the same function we are calling the ImageHandler which gets the image from the session as mentioned above and write the image to response stream. Once the operation is over this function maps the source to the image control in the client side.
While calling the Image Handler sometimes in certain cases the browser caches the response stream due to which we may face the problem in refreshing the images. To overcome this you can see In the same script I have used a function to generate a random number which basically used to get the unique URL to call the ImageHandler and overcome the response caching issue.
I have almost explained the entire functionality still lets look into the ImagePreviewHandler and Code Behind part of the application.
1: protected void OnAsyncFileUploadComplete(object sender, AsyncFileUploadEventArgs e)
2: {3: if (asyncFileUpload.FileBytes != null)
4: {5: Context.Session.Add("SessionImage", asyncFileUpload.FileBytes);
6: } 7: }1: <%@ WebHandler Language="C#" Class="ImageRequestHandler" %>
2: using System;
3: using System.Web;
4: 5: public class ImageRequestHandler : IHttpHandler, System.Web.SessionState.IRequiresSessionState
6: {7: public void ProcessRequest(HttpContext context)
8: { 9: context.Response.Clear(); 10: 11: if (context.Request.QueryString.Count != 0)
12: {13: byte[] imageData = context.Session["SessionImage"] as byte[];
14: 15: if (imageData != null)
16: { 17: context.Response.OutputStream.Write(imageData, 0, imageData.Length);18: context.Response.ContentType = "image/JPEG";
19: } 20: } 21: } 22: 23: public bool IsReusable {
24: get {25: return false;
26: } 27: } 28: 29: }In the first snippet I have given the code behind of the ASP.NET page, which simple saves the image byte array into the Session in the OnUploadedComplete event of AsyncFileUpload control. This image byte array is used later in Image Handler to process further.
And finally in the second snippet I am showing the ASP.NET Generic Handler, in ProcessRequest I am fetching the image byte array from the Session and writing the image to the response of the page. A part from implementing IHttpHandler, I am also deriving the System.Web.SessionState.IRequiresSessionState, which provides me the ability to read and write to the session. This is very important in our case since we are using session variable to read the images in the Image Request Handler.
And that all we need. You can download the code from here.
Link: https://docs.google.com/file/d/0BzIjFd_Ps-MSaUhwdzl6NXRQMVE/edit?usp=sharing

The ASP.NET MVC Toolkit is currently provided as part of the ASP.NET 3.5 Extensions Preview: http://www.asp.net/downloads/3.5-extensions/
5 March 2008, at Mix08, CTP #2 was released:
The readme includes details of the extensive API changes and how to update existing (CTP #1) projects.
May 27, 2008: CTP3 is released
The following is a list of blog posts on advanced topics.
In my previous post, you have seen the paging example, but there is one small problem you may face, if you are using ControlParameter or QueryStringParameter, for instance take a scenario when you are using ASP.NET AJAX and you have GridView and Search button in update panel.
On page load, the ObjectDataSource will take the default parameters from the DropDownList and QueryString, but problems comes when we want to click Search Button to get the changed values of the DropDownList or the QueryString without posting the page again.
Generally to refresh the data of ObjectDataSource you often write
ObjectDataSource1.Select();
On Click of Search Button.
But hold on this is only good if you want to see the changed data from the database or Rebind the ObjectDataSource, but this will not pass the current value from the controls or query string as a parameter to the database Query or Procedure. Resulting in which you will keep getting the existing query result only, so here is the actual code below for which I have written such a big story.
GridView1.DataBind();
Yes just one line code, don't worry this internally calls the ObjectDataSource1.Select(), but will give you the desired result, I hope this will help you.
Thanks
~Brij</
<
asp:History ID="History1" runat="server" OnNavigate="History1_Navigate">
</asp:History>
7. Open the codebehind and add the following piece of code
protected
void History1_Navigate(object sender, Microsoft.Web.Preview.UI.Controls.HistoryEventArgs args)
{
int startPage = 0;
if (args.State.ContainsKey("StartPage"))
{
startPage = (
int)args.State["StartPage"];
}
GridView1.PageIndex = startPage;
}
protected
void GridView1_PageIndexChanged(object sender, EventArgs e)
{
History1.AddHistoryPoint(
"StartPage", ((GridView)sender).PageIndex);
}
And thats it!!! You are ready to go...
This code uses GridView Paging, to demonstrate the HistoryControl
You can download the running sample from the here, C# Code, VB.NET Code
You can also refer my previous post
Using ASP.NET 3.5 Extensions History Control for complete Samples and Videos.
Sorry for the my code formatting, I tried to explain the steps, I hope this will help you.
This post will provide useful links on how the ASP.NET Extensions Preview allows control over the Browser back button in Ajax. Normally this is not possible using AJAX Controls in WebBrowsers, because AJAX Control's partial postback is not added to the history of Web Browser.
Note : ASP.NET AJAX Extensions are available in the ASP.NET 3.5 Extensions Preview (December 2007).
Watch the video | Download the video | Get VB code or C# codeImportant Links :
http://www.asp.net/AJAX/downloads/
http://www.bestechvideos.com/2008/06/10/introduction-to-asp-net-ajax-history
http://www.asp.net/learn/ajax-videos/video-149.aspxOne problem faced by a typical AJAX application is that a partial page update is not added to the history of the Web browser. This means that the browser’s Back button does not move back one AJAX step, but moves back one entire document, which is unlikely to be what the user expects. The below code could be written by a developer in response to a selection change within a list to to add the previous list selection to the browser's history via Nikhil's "HistoryControl":.
private void ContentList_SelectedIndexChanged(object sender,
EventArgs e)
{
history.AddEntry(contentList.SelectedIndex.ToString();
}
private void HistoryControl_Navigate(object sender, HistoryEventArgs e)
{
int selectedIndex = 0;
if (String.IsNullOrEmpty(e.Identifier) == false) {
selectedIndex = Int32.Parse(e.Identifier);
}
// Update the content being displayed in the page
contentList.SelectedIndex = selectedIndex;
// Mark the update panels as needing an update
mainUpdatePanel.Update();
}
The ASP.NET DataGrid is a popular control to display data in a table form with editing, paging and sorting capabilites.
However it is only suitable to display single DataTables - there is no support for parent-child relations.
To create a control that provides the standard DataGrid functionality and at the same time can display parent-child relations using templates to display the child elements.
Create a custom control called HierarGrid that derives from the DataGrid and a custom DataGridColumn called HierarColumn.
The HierarGrid takes a DataSet that contains relations between the tables.
While iterating over the parent table it checks the related tables for child rows and if one is found it dynamically loads a template for the child
row(s)The template is rendered invisibly into the custom HierarColumn and when the user clicks the plus icon, the template content is copied via JavaScript into a newly created TableRow.
A ready-to-use assembly (including help file).
A step-by-step tutorial that explains the usage of the HierarGrid is available on ASPAlliance
The demo that is mentioned in the article shows the usage of this control.
Sourcecode for the Demo (C#) or Sourcecode for the Demo (VB)
A really advanced sample application with documentation that shows filtering, sorting, paging, exporting with the HierarGrid was written by Nigel Parham. Please note that it is provided as-is like all downloads on this site.
A simple demo that shows editing in the HierarGrid.
And finally some snapshots showing real-life samples of the HierarGrid: Snapshot 1 Snapshot 2 Snapshot 3
When I first posted my first Ajax links on this blog, some of my friends asked me to post more basics of Ajax, so that they can use the link more effectively, so today while surfing web I found very good topic on Ajax Basics originally posted on 4GuysfromRolla.com by Scott Mitchell. I hope this will help.
You can find the download links of Ajax components, samples and other utilities on my previous blog post
http://tutorials.indianjobs.co.in/2008/01/aspnet-ajax-useful-links.html
Introduction
Over the past several years web developers have started using JavaScript to make asynchronous postbacks to the web server that only transmit and receive the necessary data; these techniques are commonly referred to as AJAX. When properly implemented, AJAX-enabled web applications offer a highly interactive user interface whose responsiveness rivals that of desktop applications. Popular web applications like the social networking news site Digg and GMail are prime examples of AJAX techniques in action.
Since AJAX involves many disparate technologies at different layers in the networking stack, implementing AJAX without the use of an AJAX framework is difficult and error-prone. Fortunately, Microsoft has released a free AJAX framework for ASP.NET developers: Microsoft ASP.NET AJAX. This article is the first in a series of articles that examines the ASP.NET AJAX framework. This installment provides an overview of AJAX technologies and looks at getting started with Microsoft's framework. Future installments will focus on specific controls and scenarios. Read on to learn more!
A Brief History of Ajax
The client-server model is an architecture that involes two actors: a client and a server. The server passively waits for a request from a client and, upon receiving such a request, processes it and returns a reply. The client is responsible for initiating requests to the server, after which is waits for and then processes the data returned in the response. Web applications are classic examples of the client-server model. The client - a web browser, most often - sends a request to a web server for a particular resource. The resource may be static content like an HTML page or an image that the web server can simply return, or it may be dynamic content like an ASP.NET page that must first be processed on the web server before its generated markup can be sent back. Regardless, the interaction is the same: the client requests a particular resource, and the server returns it, be it the binary content of a JPG image or the HTML of a rendered ASP.NET page.
One drawback of the client-server models is latency. Clients must periodically communicate with the server to update the server with the user's input, or to retrieve the latest data from the server. During these periods, the user must wait while the request/response lifecycle plays out. This delay is most clearly evidenced in ASP.NET applications when a postback occurs. Imagine an eCommerce website that lists products in a grid whose contents can be sorted and paged through. However, stepping to the next page requires a postback to the server in order to retrieve the next page of products. Consequently, moving to the next page introduces a delay in the user experience that can take anywhere from less than a second to several seconds, depending on many factors (the user's Internet connection speed, the network congestion, the server load, the database query duration, and so on).
The main culprit here is that the postback requires that all of the page's form fields be sent back to the server and that the entire web page's content be returned to the browser. This volume of exchanged data is overkill since all that is really needed by the client is information about the next page of products. AJAX mitigates these latency issues by using JavaScript to make asynchronous postbacks to the web server; these postbacks transmit and receive the minimum amount of data necessary to perform the requested operation. For a more thorough background of AJAX, be sure to read Jesse James Garrett's essay where he coined the term "Ajax": Ajax: A New Approach to Web Applications.
There are a number of AJAX frameworks available. Most ASP.NET control vendors offer commercial AJAX implementations, and there are many open source libraries as well. In early 2006 Microsoft released its own AJAX framework, Microsoft ASP.NET AJAX, which is the focus of this article series.
An Overview of Microsoft ASP.NET AJAX
Microsoft's ASP.NET AJAX framework was designed to work with ASP.NET 2.0 and future versions; it does not work with ASP.NET version 1.x applications. The ASP.NET AJAX framework will ship with Visual Studio 2008 and ASP.NET version 3.5. ASP.NET 2.0 developers, however, need to download and install the framework from Microsoft's website; the "Getting Started with Microsoft ASP.NET AJAX" section later in this article includes a discussion on installing ASP.NET AJAX in a 2.0 environment.
The ASP.NET AJAX framework consists of client-side and server-side logic. There are a bevy of JavaScript libraries that simplify initiating an asychronous postback and processing the response from the server. The client-side libraries also include classes that mimic the .NET Framework's core classes and data types. The server-side components include ASP.NET controls that, when added to a page, implement various AJAX techniques. One such example is the ScriptManager control, which adds references to the client-side script in the page, so that the browser requesting the ASP.NET page downloads the appropriate JavaScript libraries as well. Consequently, you'll use the ScriptManager on any ASP.NET page where you want to utilize the ASP.NET AJAX framework.
In addition to the ScriptManager control, the ASP.NET AJAX framework includes a handful of other server-side controls, such as the UpdatePanel, the Timer, and the UpdateProgress controls. The UpdatePanel control allows you to define a portion of the page that will be updated by an asynchronous request. In short, it allows you to make partial postbacks rather than a full page postback. This improves the responsiveness of the page in two ways: first, when a partial postback occurs only the data relevant to that UpdatePanel is sent to the server, and only the corresponding data is returned; and, second, the partial page postback does not cause the entire page to be "re-drawn" by the browser, so there's no "flash" that is all too common when making full postbacks.
The UpdatePanel is one of the core pieces of the ASP.NET AJAX framework, and one which we will be examining later on in this article. Once an UpdatePanel has been added to a page, you can add the standard ASP.NET web controls - TextBoxes, Buttons, GridViews, DropDownLists, and so on - and they will automatically take advantage of AJAX techniques. For example, if you have a Button and a TextBox in an UpatePanel and the Button is clicked, a partial postback will occur. The Button's Click event handler will be called on the server-side, as expected, and the value of the TextBox's Text property can be accessed as usual. Moreover, any other Web controls within the same UpdatePanel can have their properties read or assigned and they will be re-rendered and their output updated in the user's browser.
In addition to the base server-side controls (the ScriptManager, UpdatePanel, Timer, and so on), Microsoft offers an additional set of interactive controls via the AJAX Control Toolkit. This toolkit includes ratings controls, sliders, modal popup windows, and so forth.
Getting Started with Microsoft ASP.NET AJAX
For ASP.NET 2.0 developers, the first step in working with Microsoft ASP.NET AJAX is to download the AJAX Extensions and, optionally, the AJAX Control Toolkit. (ASP.NET 3.5 developers will already have the ASP.NET AJAX framework installed.)
Note: This article only looks at working with the AJAX Extensions (the core of the framework) and leaves the Control Toolkit for a future installment.
To download the ASP.NET AJAX 1.0 framework, visit this page and click the Download button. The ASP.NET AJAX framework is packaged up as an MSI file. Once you've downloaded the MSI file to your computer, double-click it to install the framework. After downloading and installing the ASP.NET AJAX framework, start Visual Studio and choose to create a New Project. In the New Project dialog box you should see a new project type named "ASP.NET AJAX-Enabled Web Application."
Creating an ASP.NET AJAX-Enabled Web Application creates a new Web Application Project with the System.Web.Extensions assembly added as a reference. The System.Web.Extensions assembly contains the core client- and server-side pieces of Microsoft's ASP.NET AJAX framework. Also, the Toolbox includes an AJAX Extensions category with the core server-side AJAX controls.
Our First ASP.NET AJAX Example: Using the UpdatePanel
The UpdatePanel is useful in situations where you only want a portion of the page to postback rather than the entire page. Such a limited postback is called a partial postback, and is easy to implement using the UpdatePanel. As you know, many ASP.NET controls can cause postbacks: Button controls, when clicked; DropDownLists and CheckBoxes, when their AutoPostBack property is set to True; and so on. Under normal circumstances, when these controls cause a postback, the entire page is posted back. All form field values are sent from the browser to the server. The server then re-renders the entire page and returns the complete HTML, which is then redisplayed by the browser.
When these controls appear in an UpdatePanel, however, a partial page postback is initiated instead. Only the form fields in the UpdatePanel are sent to the server. The server then re-renders the page, but only sends back the markup for those controls in the UpdatePanel. The client-side script that initiated the partial postback receives the partial markup results from the server and seamlessly updates the display in the browser with the returned values. Consequently, the UpdatePanel improves the reponsiveness of a page by reducing the amount of data exchanged between the client and the server and by "redrawing" only the portion of the screen that kicked off the partial page postback.
Let's take a look at the UpdatePanel in action. The following demo, which is downloadable at the end of this article, shows a simple example. The UpdatePanel in the demo includes only two controls: a Label and a Button. The Label Web control displays the text of a randomly selected joke. Clicking the Button loads a new randomly selected joke into the Label. If you are following along at your computer, start by adding a new ASP.NET page to the ASP.NET AJAX-Enabled Web Application we created back in the "Getting Started with Microsoft ASP.NET AJAX" section.
Whenever we use the ASP.NET AJAX framework in a page, we need to start by adding a ScriptManager control, so start by adding a ScriptManager to the page. Next, add an UpdatePanel to the page. Within that UpdatePanel, add a Label control and a Button control. After performing these steps, the declarative markup in your web page should look similar to the following:
<asp:ScriptManager ID="myScriptManager" runat="server"> |
At this point, all that remains is to write the server-side code. When the page is first loaded we want to set the JokeText Label's Text property to a randomly selected joke; likewise, whenever the NewJokeButton is clicked, we want to refresh the Label's Text property with a new joke.
protected void Page_Load(object sender, EventArgs e) |
At this point we have a page that will utilize AJAX techniques to make a partial page postback when the Button in the UpdatePanel is clicked. Consequently, clicking the "Show Me a Random Joke!" button displays a new joke promptly without having the entire page refresh. Granted, this is an overly simple example since the page already is very lightweight, but this concept can be extended to more real-world scenarios (and will be, in future installments of this article series). For example, you might have a page that has several grids on it showing a plethora of data. You could place each grid in its own UpdatePanel. That way, when a user sorted or paged a grid, a partial postback would occur and the particular grid could be paged or sorted without requiring a full postback.
The takeaway here is that implementing AJAX techniques in an ASP.NET application using the ASP.NET AJAX framework is remarkably easy. The ScriptManager and UpdatePanel controls automatically handle all of the complexities involved with initiating the asynchronous postback and displaying the returned data.
Looking Forward...
This article only looked at a simple UpdatePanel example. In real-world scenarios, however, things aren't always as simple. For example, we might want to have some event external to the UpdatePanel trigger a partial postback. We've not yet looked at working directly with the client-side AJAX libraries; nor have we explored the wealth of controls in the AJAX Control Toolkit. These, and many more topics, You can find the download links of Ajax components, samples and other utilities on my previous blog post
http://tutorials.indianjobs.co.in/2008/01/aspnet-ajax-useful-links.html
Happy Programming!