Archive for category Basic Level

Ajax File Upload With ASP.NET Using Valums’ Script

Ajax file upload is a very popular extension to all ASP.NET web applications. Thanks to ajax it’s possible to upload files without page reload. On top of that user experience can be improved by features like progress bar, drag and drop or possibility to select multiple files at once. ASP.NET developer to incorporate ajax file upload extension has to cope with two major challenges:

  1. Find the best, the easiest to integrate and the easiest to tweak JS library
  2. Integrate the library with actual ASP.NET application

In this tutorial I will show you how to integrate ASP.NET application with ajax file upload script created by Andrew Valums. I don’t know if this is the best script available out there, but for sure it’s really good. It’s easy to integrate with ASP.NET, easy to tweak and style in a custom way. Here is how to do it:

How to integrate Valums’ Ajax File Upload Script with ASP.NET

First step is to download the latest version from Valums’ site. Here are essential files to use:

  • fileuploader.css – default styles, it’s a good starting point to tweak in future
  • fileuploader.js – ajax file upload script, this is where the entire logic is
  • loading.gif – loading animation, small but cool thing, it’s required by default styles

I have put the above files in the following location in my application:

  • [root]\Images\loading.gif
  • [root]\Scripts\fileuploader.js
  • [root]\Styles\fileuploader.css

On top of that I have added a few additional files:

  • [root]\FileUpload.aspx – this is the file where user can upload files. On this page ajax file upload script will be used.
  • [root]\FilesUploader.cs – this is http handler which will receive the files, save them and reply to ajax script with appropriate status (success or error). Please remember that http handler to work has to be registered in web.config.

ASP.NET solution with all of the above files you can download from here. I recommend doing so as it will make learning process easier.

Second step is to create ASPX page with upload form. There are three essential parts:

  1. Include all relevant scripts and styles:
    <script src="Scripts/fileuploader.js" type="text/javascript"></script>
    <link href="Styles/fileuploader.css" rel="stylesheet" type="text/css" />
  2. Add HTML in place where upload form should be:
    <div id="file-uploader-demo">
       <noscript>
          <p>Please enable JavaScript to use file uploader.</p>
          <!-- or put a simple form for upload here -->
       </noscript>
    </div>
  3. Enable ajax file upload script:
    <script type="text/javascript">
       function createUploader() {
          var uploader = new qq.FileUploader({
             element: document.getElementById('file-uploader-demo'),
             action: 'FilesUploader.html',
             debug: true
          });
       }
    
       // in your app create uploader as soon as the DOM is ready
       // don't wait for the window to load
       window.onload = createUploader;
    </script>

In the last step, in line 4 script expects to get an ID of div within which form will be automatically added. In next line, it’s specified URL where the form and files will be posted to.

On this stage page for end visitor is ready, it should even render correctly. But it won’t work if you try to upload something. The missing thing is a “thing” on server side which will take uploaded files and save them somewhere (filesystem, database).

Third step is about adding http handler which will receive uploaded files. Here is a code to do that:

public class FilesUploader : IHttpHandler
{
   #region IHttpHandler Members

   public bool IsReusable
   {
      get { return true; }
   } 

   public void ProcessRequest(HttpContext context)
   {
      HttpRequest request = context.Request;

      if (IsIE9(request))
      {
         byte[] buffer = new byte[request.ContentLength];
         using (BinaryReader br = new BinaryReader(request.Files["qqfile"].InputStream))
            br.Read(buffer, 0, buffer.Length);

         string filename = Path.GetFileName(request.Files["qqfile"].FileName);
         File.WriteAllBytes(request.PhysicalApplicationPath + filename, buffer);

         context.Response.Write("{success:true}");
         context.Response.End();
      }
      else
      {
          byte[] buffer = new byte[request.ContentLength];
          using (BinaryReader br = new BinaryReader(request.InputStream))
             br.Read(buffer, 0, buffer.Length);

          File.WriteAllBytes(request.PhysicalApplicationPath + request["qqfile"], buffer);

          context.Response.Write("{success:true}");
          context.Response.End();
       }

       context.Response.Write("{error:\"Upload failed! Unexpected request.\"}");
       context.Response.End();
   }

   private bool IsIE9(HttpRequest request)
   {
      return request["qqfile"] == null;
   }

   #endregion
}

IE9 handles uploaded files in a completely different way than other browsers. Therefore major if checking if file has been uploaded in IE9 is required. Depending on that, there are different methods to access data like file name and input stream.

Uploaded files are copied from request to array of bytes in lines 16 to 18 (for IE9) and 28-30 (for other browsers). In line 21 and 32 array of bytes is saved to a file. Name of file comes from query parameter in majority of browsers. By default name of query parameter is qqfile. File in the above case will be saved in root folder of ASP.NET application. Here is screen showing how the request looks like in firebug:

ASP.NET and Ajax Files Upload

ASP.NET and Ajax Files Upload

After saving file, in lines 23-24 and 34-35 http handler responds to the ajax file upload script with information that operation was successful. In lines 38 and 39 is an example how to send to the script information about an error.

One more thing – remember please that to make http handler work, it has be registered in web.config:

<httpHandlers>
<add verb="POST" path="FilesUploader.html" type="FirstTestWebApp.FilesUploader"/>
</httpHandlers>

After step three, you should be able to upload a file, server should respond with appropriate response, files should be saved in application root folder. Only one small thing has to be done – you might have noticed that on this stage, loading.gif is not displayed when file is being uploaded.

In fourth step you have to tweak fileuploader.css file to make sure it finds the loading.gif animation. Look for .qq-upload-spinner class, this is where you have to update path to the file.

In this tutorial I have showed you how to integrate ASP.NET application with Valums’ ajax file upload script. On Valums’ page you will find all the options which scripts offers. I will list a few, the most interesting ones:

  • ability to validation based on extension of the files
  • validation based on file size
  • ability add custom query parameters to each upload
  • there is also an option to override messages and to trigger custom functions on events like upload complete, upload in progress, on submit or on cancel.

Once again, you can download full, working, ASP.NET with ajax file upload solution from here to experiment with.

If this tutorial was useful for you, please share it with you friends on twitter, facebook or google plus … whatever works best for you.

VN:F [1.9.14_1148]
Rating: 8.5/10 (14 votes cast)

1 Comment

Button Click Event via Ajax With jQuery

In this post you will see how easy you can simulate button click event via ajax and this way call some ASP.NET server side method. There are number of scenarios in which this trick can be useful but for me the most appealing one are asynchronous autosaves. You have seen it in number of places for sure – basically whenever you give user an option to enter long piece of content, it’s a good practice to implement autosave, just in case, to prevent user’s content from disappearing because of browser crash or session timeout.

Okey, so here is an example how to get asynchronous autosaves working.

Step 1 – Get HTML ready

HTML is very straightforward, all you need is a textarea and a button. Of course you don’t need any button to have autosaves working, button will be used to save final version.

<h3>This is AutoSave demo!</h3>
<div>
<textarea id="ContentTextarea" cols="50" rows="10"><%=HttpContext.Current.Session["UserContent"]%></textarea>
<br />
<button id="SaveContentButton">Save</button> <span id="autosaveUpdates"></span>
</div>

There are two additional elements:

  1. span autosaveUpdates – this is where I will show updates to a user, it’s nice to inform that everything went fine and autosave actually works
  2. server side call to HTTP Session – I’m going to keep autosaved content in HTTP session, this is definitely not a production viable option, but for this example it will work

Step 2 – ASP.NET method which saves data

There are two things which you need to do to make your ASP.NET method available for jQuery and Ajax calls:

  • method has to be public and static,
  • and you need to add [WebMethod] attribute

Here is an example with very basic code which stores content in HTTP Session:

[WebMethod]
public static void SaveContent(string content, bool autosave)
{
    if (autosave) {
        HttpContext.Current.Session["UserContent"] = content;
    }
    else {
        // TODO save data to a database
        HttpContext.Current.Session["UserContent"] = String.Empty;
    }
}

Step 3 – Button Click Event via Ajax

Before going to autosave functionality, I will show you how to call button click even via ajax with jQuery. So firstly, this is the function which will call ASP.NET method (from step 2):

function SaveDataViaAjax(autosaveMode) {
    $("#autosaveUpdates").html("Saving ... ");

    methodURL = "/AutoSave.aspx/SaveContent";
    parameters = "{'content':'" + $("#ContentTextarea").val() + "', 'autosave':'" + autosaveMode + "'}";

    $.ajax({
        type: "POST",
        contentType: "application/json; charset=utf-8",
        url: methodURL,
        data: parameters,
        dataType: "json",
        async: true,
        success: function (data) {
            if (autosaveMode) {
                $("#autosaveUpdates").html("Autosave at " + Date().toLocaleString());
            }
            else {
                $("#autosaveUpdates").html("Data have been saved at " + Date().toLocaleString());
            }
        },
        error: function (result) {
            alert("Due to unexpected errors we were unable to load data");
        }
    });
};

This function will be used to save data after manually clicking on the button and also to autosave content. A few words of explanation:

  • URL to the ASPX page and method is: ‘/AutoSave.aspx/SaveContent’
  • I need to pass two parameters as this is exactly what is expected by SaveContent() method – content and autosave
  • $(“ContentTextarea”).val() returns value of textarea.
  • $.ajax() method is responsible for all the ajax calls mechanics.
  • please note that ajax() function is configured to make a asynchronous call, hence user interface won’t be blocked even in case when server will need a few seconds to respond.
  • success function will be invoked when entire ajax call went fine and error in other case.
  • I use simple jQuery selectors to find relevant tags.

I hope that the rest is self-explanatory. If not – let me know!

Now, we need to set this function to be called after clicking on the button, this code will do it:

$(document).ready(function () {
    $("#SaveContentButton").click(function (event) {
        SaveDataViaAjax(false)
        event.preventDefault();
    });
});

Step 4 – Autosaves with jQuery

And final step where I just need to do 2 things :)

  1. Define AutoSave function
  2. Tell Java Script to call the AutoSave function every 5 seconds

And here is code which will do all of that:

$(document).ready(function () {
    window.setInterval(Autosave, 5000)
});

function Autosave() {
    SaveDataViaAjax(true);
}

And this is it, it all together should work like a charm :) Essential here is usage of setInterval() function which takes as a parameter name of the function which should be invoked and interval of time how often give function should be invoked. If you like ajax updates then I recommend you reading about  about modules and ajax updates every X seconds, you will find more details there.

Conclusions

After reading this post you should know how to:

  • simulate button click event via ajax and jQuery
  • call ASP.NET method via Ajax after clicking on a button – ajax() jQuery function
  • call server-side method periodically with setInterval() function
  • create methods in ASP.NET pages which can be invoked by jQuery

And here is the final effect:

Button Click Event via Ajax, jQuery And ASP.NET Autosave
VN:F [1.9.14_1148]
Rating: 8.6/10 (5 votes cast)

1 Comment

How To Use Basic jQuery Filters With HTML List (part 2)

In my previous post I have given you a few examples of the most basic jQuery filters. In this post I will dig a bit deeper to show you what else is possible.

Just to recap quickly, so far I have mentioned about following selectors:

  • :first – selects first element
  • :last – selects last element
  • : odd – selects all odd elements
  • :even – selects all even elements

And now a few new ones, but before I will jump to that, here is an HTML code which I use to play with:

<h2>
    Here is my magic list
</h2>
<p>
    <ul>
        <li>first point</li>
        <li>second point with an image: <img src="Images/icon_smile.gif" /></li>
        <li>third point</li>
        <li>fourth point</li>
        <li>fifth point</li>
        <li>sixth point</li>
    </ul>
</p>

Task 1: Our first taks is to add custom colour to the third and fifth element only, here is jQuery code which you can use:

$(document).ready(function () {
    $("ul.magicList > li:eq(2), ul.magicList > li:eq(4)").css("color", "red");
});

And here is the result:

basic jQuery filters

A few words of explanation:

  • li:eq(2) – our job was to select third element so you may ask why there is ’2′ passed as a paramater? That’s because index is zero-based. So first element has index 0, for second element index is 1 etc.
  • ul.magicList > li:eq(2), ul.magicList > li:eq(4)” – comma in the middle means logical OR. So it can be translated into: find third element OR fifth element.

Task 2: Now our objective is to select all elements starting from the second one. In other words … all except of the first one. There are two options which will give exactly the same effect:

$(document).ready(function () {
    $("ul.magicList > li:gt(0)").css("color", "red");
});

and second option:

$(document).ready(function () {
    $("ul.magicList > li:not(:first)").css("color", "red");
});

And here are the results:

jQuery filters and selectors

Explanation:

  • selector :not() allows you to invert selection, so you can select all elements that do not match the given selector, in our case :first
  • selector :gt() requires parameter, zero-based index. GT stands for “greather than”. In out case we want all elements where index is greather than 0. Hint: there is also another similar selector – lower than :lt() which works in analogical way.

Task 3: this one is more interesting … add custom colour for all elements which contain an image. Even though it may sound like a much more complicated job, in fact you can do it really easily:

$(document).ready(function () {
    // set custom style for all elements containing image
    $("ul.magicList > li:has(img)").css("color", "blue");
});

Explanation:

  • selector li:has(img) will return all LI elements conatining IMG tag. Of course you can use this selector to find any tag.

Task 4: the hardest task … add custom colour for every third element. So 3rd, 6th, 9th … elements should get a custom colour. jQuery doesn’t have a predefined selector for it, so in this case we have to implement it on our own. Luckily, it not a rocket science:

$(document).ready(function () {
    // set color only for every third element
    $("ul.magicList > li")
        .filter(function (index) { return index % 3 == 2; })
        .css("color", "red");});

Final result:

jQuery filters and selectors

Explanation:

  • after selecting all LI elements (“ul.magicList > li”) you can filter results with your own function which has to be passed as a parameter: filter(function (index) { return index % 3 == 2; })
  • your custom function is expected to return true for all elements that you want to include and false for element which you want to reject
  • parameter for your functions ‘index‘ is zero-based which means that for third element index is 2. 2 modulo 3 is 2. For sixth element index is 5, 5 modulo 3 is 2. You see how it works now?

I hope it all make sense to you. If not, leave a comment I will try to help! :)

VN:F [1.9.14_1148]
Rating: 10.0/10 (2 votes cast)

, ,

3 Comments

How To Use Basic jQuery Filters With HTML List

In this post I would like to show you how you can make use of jQuery selectors and filters to manipulate HTML list. Here is the starting HTML to play with:

<h2>
    Here is my magic list
</h2>
<p>
    <ul class="magicList">
        <li>first point</li>
        <li>second point</li>
        <li>third point</li>
        <li>fourth point</li>
        <li>fifth point</li>
        <li>sixth point</li>
    </ul>
</p>

Please note that on ul tag has a CSS class magicList defined. It’s useful to have a unique CSS class or ID defined because it makes writing selectors much easier. Now, having magicList CSS class defiend, you can use following jQuery selector to get list of all elements:

$(document).ready(function () {
    $("ul.magicList > li").css("color", "green");
});

A bit of explanation:

  • selector $(“ul.magicList”) will return all ul tags where CSS class equals ’magicList’
  • selector  $(“ul.magicList > li”) will return all li tags within ul tag where CSS class is ‘magicList’
  • css(“color”,”green”) – functions css() setts attribute color to provided value, in this case ‘green’

As a a result our HTML will look like this:

jQuery selectors and HTML list

Now, let’s try to make it a bit more sophisticated – odd elements can stay green, but even elements should be red :) Here is a jQuery code which can do that for you:

$(document).ready(function () {
    $("ul.magicList > li:odd").css("color", "green");
    $("ul.magicList > li:even").css("color", "red");
});

In the above case I have used jQuery filters to limit set of elements to the one which I need:

  • selector $(“ul.magicLIst > li”) will return all li tags and by using filter “:odd” it’s possible to take only odd elements and remove the even ones.
  • for even elements filter to use is “:even”

Okey, let’s add another requirement – first and last elemets should be blue. As you can probably guess already there are additional jQuery filters which will return for you first and last element:

$(document).ready(function () {
    $("ul.magicList > li:odd").css("color", "green");
    $("ul.magicList > li:even").css("color", "red");
    $("ul.magicList > li:last").css("color", "blue");
    $("ul.magicList > li:first").css("color", "blue");
});

And here is the final result:

jQuery filters and HTML list

In this post I wanted to give you an idea how powerful and useful jQuery is and how easy you can manipulate HTML list with it. Of course ,the same results you can achieved in many different ways within ASP.NET  but none of them is not as simple as jQuery one.

In the next posts you will find more advanced filters which means more fun and more options to get exactly what you need! :)

VN:F [1.9.14_1148]
Rating: 10.0/10 (2 votes cast)

, ,

2 Comments

How To Enable IntelliSense For jQuery in Visual Studio 2010

VS IntelliSense doesn't know anything about jQueryBy default IntelliSense in Visual Studio doesn’t know anything about jQuery. So for instance if you try get some help as soon as you type ‘$’ IntelliSense won’t suggest you anything useful. You can see that on the right.

Luckily enabling support for jQuery is very simple, I will show you how to do it in a few simple steps, but first let’s make sure that we are in the same starting point.

  1. Make sure that you have jQuery included in your project. If you created your application by choosing ‘ASP.NET Web Application’ then check folder Scripts. Look for files jquery-1.4.1.js or jquery-1.4.1.min.js – it should be there. If for some reason those files are not there, you can always download them form jQuery.com and manually add to the project.
  2. Make sure that jQuery documentation for Visual Studio is also included. Look for file jquery-1.4.1-vsdoc.js. Again it should in Scripts folder. If not, download for jQuery.com.

How to enable IntelliSense for jQuery

  1. Create new JScript file
  2. Drag & drop jquery-1.4.1-vsdoc.jsfile into the new javascript file.

    IntelliSense drag-and-drop

    when this is done your JS file should loke like this:

    /// <reference path="jquery-1.4.1-vsdoc.js" />
  3. Now you can start using IntelliSense, here are a few examples:

    jQuery IntelliSense
    jQuery IntelliSense 2

    jQuery IntelliSense 3

  4. Enjoy! :)

jQuery 1.6.2 Update

Currently the latest version if jQuery is version 1.6.2. Here you can download jQuery 1.6.2 documentation for Visual Studio.

VN:F [1.9.14_1148]
Rating: 7.7/10 (3 votes cast)

No Comments