The Microsoft Ajax Library

I’m a big Fan of the new new Microsoft Ajax library. It combines what was previously Asp.net AJAX and the Ajax Control toolkit into one library. As an added bonus, the new library contains a client side only version of all the controls in the control toolkit. So that means you can use any of the ui enhancements in asp.net mvc pages and really any web based framework.

The library is still in beta, but it’s already showing great promise.

In this post I’m going to be going over some customization features of the client side calendar control. You can read the basics about using the calendar control here .

The first issue we are going to tackle is how to set the date format. By default the calendar control returns a string with the format “MM/dd/yyyy”. However, this may not work for all locales and fortunately the control is configurable. We can easily change the format by calling the set_format function and passing in the desired format.

Sys.require(Sys.components.calendar, function () {
    var calendarControl = Sys.create.calendar("#travelDate");
    calendarControl.set_format("dd/MM/yyyy");
});


Now when you select a date it should show up in the dd/MM/yyyy format. Selecting December 6th, 2009 in the calendar now returns the string “06/12/2009”.
ajax-library-ddmmyyy

The second calendar feature I’d like to go over is how to use an html button to show the calendar. It’s actually quite simple and basically you just have to add an onclick handler to the button. Then in the handler function call the controls show() method. Let’s expand on our previous example and add a “Show” button.

First lets add the html markup:

<input id="travelDate" />
<input type="button" onclick="showCalendar()" name="btnShowDate" id="btnShowDate" value="Show" />

Notice, btnShowDate has an onclick property that’s set to “showCalendar()”. This tells the browser to fire the showCalendar javascript function when the button is clicked.

Now, here’s the javascript code that should go in the head section:

<script type="text/javascript">
    var calendarControl;
    Sys.require(Sys.components.calendar, function () {
        calendarControl = Sys.create.calendar("#travelDate");
    });
    function showCalendar() {
        calendarControl.show();
    }
</script>

The calendarControl variable is declared outside of the Sys.require function scope. This allows us to access it later from showCalendar. As you can see showCalendar is a very simple function and really just a wrapper for calendarControl.show(). There is no reason why you can’t call calenderControl.show() directly in the onclick, but I like to keep things separated this way in case I have to make modifications later or decide to do any other processing before showing the form.

As you can see the calendar is a very powerful client side control. Although the library is still in beta, I’m very excited to learn more about it and create some really awesome javascript pages.

Advertisements