Archive for category Intermediate Level
jQuery UI Datepicker With ASP.NET
Posted by admin in Intermediate Level, jQuery Plugins, jQuery UI and ASP.NET on July 23, 2011
jQuery UI Datepicker is another great widget, extremely useful on forms, which can be easily integrated with ASP.NET. There are tones of different datepickers available almost everywhere so big question is why this one is better than other ones?

jQuery UI DatePicker Themes
Here are a few reasons:
- jQuery UI is very well tested
- jQuery UI is based on jQuery framework and very well integrated
- there are 20+ themes available, ready to use, which you can take and make the datepicker to look consistent with your site
- even if available themes are no good for you, you can easily customize it
- it’s easy to integrate with ASP.NET
- it’s flexible, you can configure it to serve you in many scenarios
On top of that, it’s my subjective opinion, but I really can recommend this plugin. I think it should cover 95% of typical scenarios which you can encounter on websites.
Okey, so let’s get started …
How to integrate jQuery UI Datepicker with ASP.NET
Step 1 – download jQuery UI on your machine. I was using version 1.8.14.
Step 2 – Make sure that your page has all the required JS and CSS files included. Datapicker has a few dependencies. Here is everything you need:
<script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script> <link href="/Styles/ui-lightness/jquery-ui-1.8.14.custom.css" rel="stylesheet" type="text/css" /> <script src="/Scripts/ui/jquery.ui.core.js" type="text/javascript"></script> <script src="/Scripts/ui/jquery.ui.widget.js" type="text/javascript"></script> <script src="/Scripts/ui/jquery.ui.datepicker.js" type="text/javascript"></script>
Step 3 – HTML Code
This part is very simplified of course just to illustrate basic concepts.
<div id="DatepickerDiv" class="demo"> Event start date: <asp:TextBox ID="txtEventStartDate" runat="server" CssClass="DatepickerInput" /><br /> <asp:Button ID="btnSave" runat="server" Text="Save" onclick="btnSave_Click" /><br /> <asp:Literal ID="litMessage" runat="server" /> </div>
Basically minimalistic version contains textbox where user will enter a date. Datepicker widget will be attached to exactly this textbox. There is also button which will submit the form and literal to display messages from server.
Step 4 – jQuery Code
$(document).ready(function () {
$(".DatepickerInput").datepicker({ dateFormat: 'dd/mm/yy' });
});
As you can see this is not very complex. In fact specifying date format is optional but I don’t like to leave date formats not specified. I have too many bad experiences from working with multilingual sites. Date format is different even between UK and US so this is one thing which I don’t want to leave for jQuery to figure out.
In this example jQuery finds textbox based on CSS class – this part is responsible for it: $(“.DatepickerInput”). Here you can read more about how to use basic jQuery filters. Datepicker is attached by calling function datepicker(). All parameters are optional, even dateFormat which I used here.
After this step you should be able to get this effect after clicking on txtEventStartDate textbox:

jQuery UI DatePicker Demo Page
Step 5 – ASP.NET Code
On server side the only missing thing is implementation of btnSave_Click() method:
protected void btnSave_Click(object sender, EventArgs e)
{
DateTime date;
if (DateTime.TryParseExact( txtEventStartDate.Text,
"dd/MM/yyyy", // example: 31/01/2011
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out date))
{
litMessage.Text = "Parsed event start date: " + date.ToShortDateString();
}
else
{
litMessage.Text = "Error: we were unable to parse the start date: " + txtEventStartDate.Text;
}
}
The most important thing to remember is to use the same date format as it was in jQuery script. You can see that there are differences in Java Script and ASP.NET data format notation. This can be confusing and is something that should be well commented! It is also a good practice to use TryParseExact() method over simply ParseExact(). And the rest I think is self-explanatory
Conclusion
jQuery UI Datepicker can be easily integrated with ASP.NET and I think should be considered as a default datepicker option for majority of websites. Example in this post shows that you need only a few lines on jQuery code to get everything working. Can you see any reason to not follow this approach?
Next steps? Two actually …
- You can also check how to integrate Autocomplete jQuery UI widget with ASP.NET
- And you can read more about configuration options which Datepicker offers.
jQuery UI Autocomplete With ASP.NET
Posted by admin in AJAX Updates, Intermediate Level, jQuery Plugins, jQuery UI and ASP.NET on July 13, 2011
In this post I want to show you how to integrate ASP.NET with jQuery UI Autocomplete widget. For those of you which don’t know what jQuery UI is here is a bit of introduction:
jQuery UI provides a comprehensive set of core interaction plugins, UI widgets and visual effects that use a jQuery-style, event-driven architecture and a focus on web standards, accessiblity, flexible styling, and user-friendly design.
From practitioner point of view – jQuery UI provides a few very nice and very useful widgets which you can really easily integrate with your application. Great example is Autocomplete widget which I will use in this post. I have found this widget very useful while implementing search functionality for my project. Of course to implement “just” search functionality where user can enter a keyword and click “search” button you don’t need much. And for sure you don’t need any fancy jQuery widgets. In my case additional requirement was to implement predictive search functionalty. That was a massive change for ASP.NET developer because out of the sudden I had to invoke search after each letter entered by a user and present it in a nice way.
Here is a great example how Google did the predictive search:

And here is another example, something like this I will show how to build in this post:

There is no component like that in Visual Studio! So the solution was to use jQuery UI Autocomplete widget.
How to integrate jQuery UI Autocomplete widget with ASP.NET
Step 1 – go to jqueryui.com and download jQuery UI. I was using version 1.8.14
Step 2 – include following JS scripts in your master page
<link href="/Styles/ui-lightness/jquery-ui-1.8.14.custom.css" rel="stylesheet" type="text/css" /> <script src="/Scripts/jquery-1.5.1.min.js" type="text/javascript"></script> <script src="/Scripts/ui/jquery-ui-1.8.14.js" type="text/javascript"></scrpt> <script src="/Scripts/ui/jquery.ui.core.js" type="text/javascript"></script> <script src="/Scripts/ui/jquery.ui.widget.js" type="text/javascript"></script> <script src="/Scripts/ui/jquery.ui.position.js" type="text/javascript"></script> <script src="/Scripts/ui/jquery.ui.autocomplete.js" type="text/javascript"></script>
On the list above are all jQuery, jQuery UI Autocomplete widget and dependencies. Please note that there is also CSS style on the list – this is required to make Autocomplete widget looks nice
Step 3 – Create a Web Service which will return predictive search results
[System.Web.Script.Services.ScriptService]
public class PredictiveSearch : System.Web.Services.WebService
{
[WebMethod]
public IList<string> GetAllPredictions(string keywordStartsWith)
{
//TODO: implement real search here!
// dummy implementation
IList<string> output = new List<string>();
output.Add(keywordStartsWith + "1");
output.Add(keywordStartsWith + "2");
output.Add(keywordStartsWith + "3");
output.Add(keywordStartsWith + "4");
return output;
}
}
This is an example of web service which returns dummy data. Your job is to take is further and integrate with your system. Good thing is that from this point it’s all .Net so something you should be comfortable with.
Step 4 – HTML Code
<div class="ui-widget">
<asp:Label ID="lblSearch" Text="Search" AssociatedControlID="txbSearchKeyword" runat="server"></asp:Label>
<asp:TextBox ID="txbSearchKeyword" runat="server" CssClass="searchinput"></asp:TextBox>
<asp:Button Text="Go!" runat="server" onclick="Search_Click" />
</div>
<asp:Literal ID="litStatus" runat="server"></asp:Literal>
As you can see HTML code is fairly straightforward. Only standard ASP.NET controls are here. Textbox txbSearchKeyword is the place where users will be entering keywords. So this is also the place where we need to add jQuery Autocomplete functionality. And that will happen in next step …
Step 5 – jQuery code
Firstly, let me show you the simplest possible implementation. It’s very simple so also a bit limited ![]()
Limitation in this case is that search results are static (there are no ajax calls to server for search results). This can work well in scenario where set of all possible options is very limited – for instance you can use it to tag content. Assumption is that set of tags is fairly constant and in total there are below 100 tags in the system.
$(document).ready(function () {
$(".searchinput").autocomplete({
source: ["test", "asp.net", "jQuery"],
minLength: 2
});
});
And here is an example which actually uses Web Service from step 3.
$(document).ready(function () {
$(".searchinput").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Services/PredictiveSearch.asmx/GetAllPredictions",
data: "{'keywordStartsWith':'" + request.term + "'}",
dataType: "json",
async: true,
success: function (data){
response(data.d);
},
error: function (result) {
alert("Due to unexpected errors we were unable to load data");
}
});
},
minLength: 2
});
});
In both examples searching for predictions will start not straight away after entering 1 letter! It will start after entering 2 letters, parameter minLength is responsible for that. You can see that behind the scene autocomplete functions calls our PredictiveSearch.asmx Web Service, in particular method GetAllPredictions(). In the next line we are passing entered letters as a parameter data.
It’s recommended to have your JS function in a separate file so that HTML code is separated from JS code.
Step 6 – Get Keyword on server side
On this stage, everything should be working now on client side. You should be able to see something this:

The only missing thing is implementation of onClick function called by “Go!” button. Implementation is again dummy, just to show you how to access all the relevant data:
protected void Search_Click(object sender, EventArgs e)
{
litStatus.Text = "Search conducted for keyword: " + txbSearchKeyword.Text;
}
And as far as I’m concerned this all what you need to integrate jQuery UI Autocomplete with ASP.NET. However here you will find more advanced tutorial showing how to customize jQuery UI Autocomplete widget.
Questions? If yes then leave a comment!
You can download the full ASP.NET project here with the jQuery UI Autocomplete integrated - it should help you with experimenting.
Easy Client Side Repeater with jTemplates Part 3
Posted by admin in Intermediate Level, jQuery Plugins on April 6, 2011
This is the third post in “Easy Client Side Repeater with jTemplates” series. Just to recap quickly – last two posts were about:
- in the first part you can find information about jTemplates plugin and an example how to build client side repeater with jQuery
- second part is showing how to bind data from ASP.NET WebService with the jTemplates client side repeater
ASP.NET developers when asked about the repeater they naturally see something like this:
<asp:Repeater ID="rptSomeRepeater" runat="server"> <HeaderTemplate></HeaderTemplate> <ItemTemplate></ItemTemplate> <AlternatingItemTemplate></AlternatingItemTemplate> <FooterTemplate></FooterTemplate> </asp:Repeater>
In the previous posts I have shown how you can represent all Repeater’s templates in jTemplates. You will find there details regarding all the templates except of the one (two actually) which are needed to achieve effect like this:
Chalange here is to set different CSS class for odd and even rows. This kind of effect is easy to implement with standard server side ASP.NET Repeater by using ItemTemplate and AlternatingItemTemplate. So how it can be reproduced with jTemplates and client side repeater?
ItemTemplate and AlternatingItemTemplate with jTemplates
Here is a small modification to the code from previous parts which is doing the trick:
{#foreach $T.d as record}
<tr class="{#cycle values=['odd','even']}">
<td><a href="{$T.record.WebSite}">{$T.record.Name}</a></td>
<td><a href="mailto:{$T.record.Organizer.Email}">{$T.record.Organizer.Name}</a></td>
<td>{$T.record.Venue.Name}</td>
</tr>
{#/for}
Essential part of the above example, and the only change, is this line: class=”{#cycle values=['odd','even']}”. This part makes sense because it’s within {#foreach} … {#/for} block. It works in a way that for the first item on the list jTemplates will take first item from {#cycle} values – in our case – ‘odd’. For the second item – jTemplates will take second element from the list – ‘even’. And for third it will start from the begining.
Final HTML code will look like this:
Questions? Leave a comment!
Easy Client Side Repeater with jTemplates Part 2
Posted by admin in Intermediate Level, jQuery Plugins, WebService on March 30, 2011
In the first part I have showed you how to use jTemplates plugin to build client side repeater. In this part I will show you how to make that work with data from ASP.NET WebService. That can be done in 3 steps:
Step 1 – Call WebService to Get Data
GetForthcomingEvents = function (successFunction) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Services/EventsService.asmx/GetTheForthcomingEvents",
dataType: "json",
success: successFunction,
error: function (result) {
alert("Due to unexpected errors we were unable to load data");
}
});
}
This is standard example of $.ajax() function usage. URL of the WebService is /Services/EventsService.asmx and function’s name is GetForthcomingEvents().
GetForthcomingEvents() function expects another function as a parameter. That function will be invoked, assuming that call to WebService went fine (success: successFunction). In the next step you will see an exemplary implementation. It won’t be a surprise to you – it is the same function which was already presented in the first part.
Step 2 – Bind Data From WebService to jTemplates template
BindDataToEventsTemplate = function (result) {
// check if jTemplates is loaded
if (!jQuery.fn.processTemplate) {
alert("jTemplates is not loaded");
return;
}
// attach and process the template
$("#Events").setTemplateElement("EventsTemplate");
$("#Events").processTemplate(result);
}
Data returned from the WebService will be passed here. Next, data will be used to “process template” and this way data will be passed to client side repeater.
Step 3 – Get to all working on document ready
$(document).ready(function () {
$("#Events").html("Loading events ....");
GetForthcomingEvents(function (result) {
if (result.d.length > 0) BindDataToEventsTemplate(result);
});
});
This is of course not the simplest possible option. I have added one if statement (if (result.d.length > 0)) to check if there are actually some events returned. I didn’t want to “execute” repeater when there are no events to display. But it’s optional step and can be omitted.
jTemplates in action
Here I want just to remind you essential part of the template which will be used to process the data
{#foreach $T.d as record}
<tr>
<td><a href="{$T.record.WebSite}">{$T.record.Name}</a></td>
<td><a href="mailto:{$T.record.Organizer.Email}">{$T.record.Organizer.Name}</a></td>
<td>{$T.record.Venue.Name}</td>
</tr>
{#/for}
For each record a row like that will be created. For more details please check first part of this post.
Bonus – The WebService
Here you can see my dummy code of the WebService
[System.Web.Script.Services.ScriptService]
public class EventsService : System.Web.Services.WebService
{
[WebMethod]
public Event[] GetTheForthcomingEvents()
{
return new Event[] { GetFirstEvent(), GetSecondEvent() };
}
private Event GetFirstEvent()
{
return new Event
{
StartDate = DateTime.Now,
EndDate = DateTime.Now,
Name = "MTS Conference",
WebSite = "http://microsoft.com",
Organizer = new Contact
{
Email = "john@ms.com",
JobTitle = "CEO",
Name = "John White"
},
Venue = new Venue
{
Address = "Alabama St. 45",
City = "Washington DC",
Name = "Medison Square Garden",
PostCode = "45-233"
}
};
}
private Event GetSecondEvent()
{
return new Event
{
StartDate = DateTime.Now,
EndDate = DateTime.Now,
Name = "Microsoft TechEd North America",
WebSite = http://www.microsoft.com/events/techednorthamerica/",
Organizer = new Contact
{
Email = "john@ms.com",
JobTitle = "CEO",
Name = "Barry Green"
},
Venue = new Venue
{
Address = "Alabama St. 45",
City = "Atlanta",
Name = "Georgia World Congress Center",
PostCode = "30303"
}
};
}
}
public class Event
{
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public string Name { get; set; }
public string WebSite { get; set; }
public Contact Organizer { get; set; }
public Venue Venue { get; set; }
}
public class Venue
{
public string Name { get; set; }
public string Address { get; set; }
public string City { get; set; }
public string PostCode { get; set; }
}
public class Contact
{
public string Name {get; set; }
public string JobTitle { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
}
Now you have all the pieces. Take it, use it, experiment with it and have fun!
I hope that it all makes sense to you … if not then please leave a comment and I will do my best to help you.
Easy Client Side Repeater With jTemplates
Posted by admin in Intermediate Level, jQuery Plugins, WebService on March 28, 2011
In this post I would like to show you how easy you can implement client side repeater. There are a few jQuery plugins which you can use for it. However I recommend using jTemplates. With jTemplates you can easily define a client side templates, here is an example:
<p style="display:none"><textarea id="EventsTemplate" rows="0" cols="0"><!--
<table>
<thead>
<tr>
<th>Event</th>
<th>Contact</th>
<th>Venue</th>
</tr>
</thead>
<tbody>
{#foreach $T.d as record}
<tr>
<td><a href="{$T.record.WebSite}">{$T.record.Name}</a></td>
<td>
<a href="mailto:{$T.record.Organizer.Email}">
{$T.record.Organizer.Name}
</a>
</td>
<td>{$T.record.Venue.Name}</td>
</tr>
{#/for}
</tbody>
</table>
--></textarea></p>
In the above example you can see that template itself is hidden for end users (display:none). Everything within HTML comments will be used. You can easily recognize elements corresponding to well known ASP.NET Repeater elements:
- everything from the very top (<table>) to {#foreach … } represents HeaderTemplate
- everything between {#foreach…} and {/#for} represents ItemTemplate
- and everything under {/#for} is a FooterTemplate
How to Bind Data to Client Side Repeater?
JS code binding data to the jTemplates repeater looks like this:
BindDataToEventsTemplate = function (result) {
// attach and process the template
$("#Events").setTemplateElement("EventsTemplate");
$("#Events").processTemplate(result);
}
Where $(“Events”) selects tag with id “Events” – this is where output will be placed. “EventsTemplate” is the name of our template – check the definition of template (first piece of code). So it’s that easy – firstly you need to set template which you want to use and secondly bind the data and ”process template”. End of story!
Just to make everything perfectly clear – here is an example of my “Events” tag where new events will be added using client side repeater:
<div id="Events"></div>
One additional tip – you can also check, just in case, if jTemplates has been correctly loaded by adding this piece of code:
// check if jTemplates is loaded
if (!jQuery.fn.processTemplate) {
alert("jTemplates is not loaded");
return;
}
In my case I have loaded data to the repeater from ASP.NET WebService. In the next post I will show you how to get it all working together – jTemplates with ASP.NET WebServices.
How to Check If jQuery Plugin is Loaded
Posted by admin in Intermediate Level, jQuery Plugins, Tips on November 9, 2010
A few days ago I was playing with jQuery plugin jTemplates. I had a tough time trying to get it working. As usual in such situation you can’t see obvious mistakes and instead you keep exploring all options which can possibly go wrong. During one of such exploration I was checking if jTemplates has been correctly loaded. Of course real problem was completely different… :)
But still, the code checking if plugin is loaded is very simple and thanks to it you have one less option to worry about. Here it is:
//check if jTemplates is loaded
if (!jQuery.fn.processTemplate) {
alert("jTemplates is not loaded");
return;
}
jTemplate has a function called processTemplate. If entire plugin was loaded correctly then this function is available. And this is exactly what is checked within if() statement. If for some reason plugin wasn’t loaded user will get an information: “jTemplates in not loaded”.
Of course you should use more user-friendly messages or deal with such problems in more elegant way. But nevertheless, checking if plugins are loaded should be a mandatory step for all developers. It doesn’t cost you much but in rare (hopefully) situations your site won’t crash because of lack of plugin which you expect to be loaded.
Modules and AJAX Updates Every X Seconds
Posted by admin in AJAX Updates, Intermediate Level, Tips on September 15, 2010
In this post I want to show you how easy you can achieve AJAX asynchronous updates with jQuery. Typical scenarios where such functionality is handy are all sorts of modules which you would like to update without reloading entire page like:
- The latest tweeter updates
- The latest comments
- Currently logged in users, or number of users online
- and so on …
In my example I will show you how to create module showing currently logged in users which will be updated asynchronously every 10 seconds.
1. Create ASP.NET Web Form Page which outputs JUST the module’s HTML
Here is ASP.NET code for my module:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CurrentlyLoggedInUsers.aspx.cs" Inherits="TestWebApp.Modules.CurrentlyLoggedInUsers" %>
<asp:Repeater ID="rptUsers" runat="server">
<HeaderTemplate><div id="loggedInUsers"></HeaderTemplate>
<ItemTemplate><a href="#"><%# Container.DataItem%></a>, </ItemTemplate>
<FooterTemplate></div></FooterTemplate>
</asp:Repeater>
Generated at <%= DateTime.Now.ToLongTimeString() %>
And code behind code:
public partial class CurrentlyLoggedInUsers : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// dummy list of users
var list = new List<String> { "john", "mark", "james", "mike", "rodney" };
rptUsers.DataSource = list;
rptUsers.DataBind();
// simulate real life scenario where it takes some time to generate the list
Thread.Sleep(2000);
}
}
As you can see it’s nothing sophisticated, very simple HTML, Repeater and dummy list of users. Good base to check how this solution works and to build on top of that later on…
2. Module and jQuery code
On other pages, where module is supposed to be located, it’s required to have only a div tag inside of which module will be loaded by jQuery:
<div id="LoggedInUsersModule"></div> <div id="LoggedInUsersModuleUpdateStatus"></div>
Second div tag will be used to indicate that AJAX update is in progress and is loading new data. It’s not a part of core solution but I think it’s something which is nice to have. It improves user’s experience.
And now jQuery code:
$(document).ready(function () {
updateLoggedInUsersModule();
window.setInterval(updateLoggedInUsersModule, 10000)
});
function updateLoggedInUsersModule() {
$('#LoggedInUsersModuleUpdateStatus').html('Loading ...').fadeIn('fast');
$('#LoggedInUsersModule').load('/Modules/CurrentlyLoggedInUsers.aspx', function(response, status, xhr) {
$('#LoggedInUsersModuleUpdateStatus').fadeOut('fast');
});
}
Explanation:
- First 4 lines a responsible for setup. In the second line I’m manually calling updateLoggedInUsersModule() function to load initial data. I don’t want to wait 10 seconds to show something on a page.
- window.setInterval() function is a JavaScript’s built-in function which will call function passed as a first parameter (updateLoggedInUsersModule() in my case) every 10 seconds (second parameter)
- In 7th line I’m updating status by setting new inner HTML and then jQuery function fadeIn() will display the element.
- 8th line is the most important line, load() function will load data from server and place it into selected element. In our case that will be div with id LoggedInUsersModule.
- Last parameter of load() function is a callback function which will be invoked after loading the data. I used this place to hide ‘Loading …’ text and this way show that operation has ended with success. Text will be hidden by fading them to transparent thanks to fadeOut() function.
What next?
- Nice thing about load() function is that you don’t necessarily have to use entire HTML generated by server. You can use jQuery selectors on that HTML in a following way: $(‘#LoggedInUsersModule’).load(‘/Modules/CurrentlyLoggedInUsers.aspx #loggedInUsers‘)
- Please remember that modules like this, with AJAX updates done every X seconds will be heavily used so it’s essential to make sure that performance is not a problem. Use a lot of caching on server-side if necessary.
Custom Validators and Asynchronous Calls to Web Service with jQuery
Posted by admin in ASP.NET Validators, Intermediate Level, Tips, WebService on September 11, 2010
Custom ASP.NET Validators give developers easy way to create validator which is tailored exactly to their needs. Last week I have encountered a scenario in which custom validator was a great solution. I was working on yet another registration form and my job was to validate if username and email address are unique with javascript. I have used Custom Validators for that because I was already using ASP.NET validators so I wanted to stick to one approach for all fields of the registration form. Within client side function I have used jQuery to call web service which will do the validation for me. The trick was to bring it all together and make sure that this solution works with asynchronous calls. Let me show it to you step by step.
1. Create validation Web Service
There are really no tricks regarding the web service. All that you have to remember is to make sure that following lines are uncommented:
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. [System.Web.Script.Services.ScriptService]
Then add methods which jQuery will call to validate if username and email are unique and therefore available:
[WebMethod]
public bool IsUsernameAvailable(string username)
{
Thread.Sleep(1000); // for tests only
return !username.StartsWith("a");
}
[WebMethod]
public bool IsEmailAvailable(string email)
{
Thread.Sleep(1000); // for tests only
return email.StartsWith("a");
}
This is of course dummy implementation but I’m sure you get my point here. One thing worth noticing is that Sleep() method on Thread has been used. That’s because in real life scenario validation like this will require a call to a database so inevitably it will be slow. Thanks to Sleep() method I wanted to make sure that response is not instant and this way simulate real life scenario.
2. Custom Validator
Basic ASP.NET code consists of a field where users will enter username and custom validator for it:
<asp:Label ID="lblUsername" runat="server" AssociatedControlID="txbUsername" Text="Username" />
<asp:TextBox ID="txbUsername" runat="server"/>
<asp:CustomValidator
ID="cuvUsernameAvailable"
runat="server"
ControlToValidate="txbUsername"
Display="Dynamic"
ClientValidationFunction="ValidateUsername"
ErrorMessage="Username is not available!"/>
As you can see custom validator requires javascript function ValidateUsername to validate username.
3. Client Side function
Within javascript function I have used jQuery to call web service and this way delegate validation there. jQuery part looks like this:
ValidateUsernameWithWebService = function (username, successFunction) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "/Services/RegistrationDataValidationService.asmx/IsUsernameAvailable",
data: "{'username':'" + username + "'}",
dataType: "json",
async: true,
success: successFunction,
error: function (result) {
alert("Due to unexpected errors validation doesn't work");
}
});
}
A few words of explanation:
- function expects two parameters – username (string) and callback function which will be called after web service invocation.
- URL to the web service is /Services/RegistrationDataValidationService.asmx, and method which will be invoked is IsUsernameAvailable
- async parameter is set to true so entire call will be done asynchronously
And finally the ValidateUsername function which will be called by the validator:
// variable to keep result of the last call to web service
var UsernameValidationResult;
// variable to keep information about username which was validated in the last call
var UsernameValidatorLastCheckValue;
ValidateUsername = function (source, args) {
// detect validation triggered by form submission
// prevent calls to web service in such scenario, return the previous result
if (UsernameValidatorLastCheckValue == args.Value) {
args.IsValid = UsernameValidationResult;
return;
}
// async check with web service
ValidateUsernameWithWebService(args.Value, function (result) {
// following 2 lines are here to make sure
// that on submit validator won't invoke call to webservice
// it will reuse data from a call which was triggered by onChange event
UsernameValidationResult = result.d;
UsernameValidatorLastCheckValue = args.Value;
// next three lines - inform validator about the result, update display
source.isvalid = result.d;
ValidatorUpdateDisplay(source);
ValidatorUpdateIsValid();
});
}
This part is a bit messy because you have to realize that validation and therefore this function will be called after entering username (onChange event) and when user click on submit button.
In the first case (onChange event) it’s fine to do the asynchronous call and get results after a second or two. However in case of form submission it’s not an option. It’s also worth noticing that in case of form submission username entered by the user hasn’t change, it was already validated. So it doesn’t make sense to validate it again. And that’s why in the above code I keep results of the last validation in the UsernameValidationResult and UsernameValidatorLastCheckValue variables.
I hope that it all make sense to you, if not then don’t hesitate to leave a comment. I will do my best to refine not clear areas. Also don’t hesitate to leave a comment even if everything is clear but you have a question or maybe something interesting to add.
How To Empower ASP.NET Repeater With jQuery
Posted by admin in Intermediate Level, Tips on August 10, 2010
As a ASP.NET developer I can imagine that you are using ASP.NET Repeater very often. It’s certainly true in my case. Repeater is probably the most useful control available in entire ASP.NET. It is great to output lists with custom template.
Here is a very simple example showing how to display list of strings as a HTML list. In code behind file I have to simply bind data to the repeater:
var list = new List() { "first point", "second point", "third point", "fourth point", "fifth point", "sixth point" };
rptList.DataSource = list;
rptList.DataBind();
And Repeater is defined in a following way:
<asp:Repeater ID="rptList" runat="server"> <HeaderTemplate><ul></HeaderTemplate> <ItemTemplate> <li><%# Container.DataItem %></li> </ItemTemplate> <FooterTemplate></ul></FooterTemplate> </asp:Repeater>
ASP.NET Repeater and dealing with CSS styles
To that point everything works great. However what was always problematic with Repeaters is manipulation with CSS styles. Quite typically there are requirements to set some custom class on a first and last element. Such requirements enforces changes in my clean code into something like this:
1. First let me update Repeater template:
<asp:Repeater ID="rptMagicList" runat="server"> <HeaderTemplate><ul></HeaderTemplate> <ItemTemplate> <asp:Literal ID="litElement" runat="server" /> </ItemTemplate> <FooterTemplate></ul></FooterTemplate> </asp:Repeater>
2. Introduction of ASP.NET Literal means that binding will be done in code behind files:
private int elementsCount = 0;
protected void Page_Load(object sender, EventArgs e)
{
var list = new List() { "first point", "second point", "third point", "fourth point", "fifth point", "sixth point" };
// this is needed to figure out which element is the last one
elementsCount = list.Count;
rptMagicList.ItemDataBound += rptMagicList_ItemDataBound;
rptMagicList.DataSource = list;
rptMagicList.DataBind();
}
void rptMagicList_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
{
var currentElement = e.Item.DataItem as String;
var litElement = e.Item.FindControl("litElement") as Literal;
var cssClassName = String.Empty;
if (e.Item.ItemIndex == 0) cssClassName = "first";
if (e.Item.ItemIndex == elementsCount - 1) cssClassName = "last";
litElement.Text = string.Format("<li class='{0}'>{1}</li>",cssClassName, currentElement);
}
}
Of course this approach works. It’s also true that from developer to developer solution for this task may vary slightly. But I think you will agree that by adding one simple requirement we had to add lots of lines of monkey code. Let’s face it … this is not a rocket science, this code is trivial and after updating a few repeaters like this … you are sick of it.
So is there a better approach? I think there is – use strong side of ASP.NET Repeater to output list and strong side of jQuery to deal with custom CSS styles!
How to empower ASP.NET Repeater with jQuery
If you use Repeater + jQuery approach then there is no need to change ASP.NET code from initial example. All you have to do is to add JavaScript file with jQuery code:
$(document).ready(function () {
$("ul.magicList > li:first").addClass("first");
$("ul.magicList > li:last").addClass("last");
});
If you are new to jQuery and not sure what this code is doing, check my older posts. Everything is explained there in a simple way:
- How To Use Basic jQuery Filters With HTML List
- How To Use Basic jQuery Filters With HTML List part 2
So to sum up … what are the benefits of this approach:
- Less code – code which you write is an absolute minimum, no monkey code
- Flexibility – jQuery has a lot to offer, ASP.NET has also a lot to offer — use strong sides of both technologies to get thinks done
- Lack of hardcoded CSS classes in code behind files – this is also important, this way you don’t need a developer to change some purely UI related issues.
- Part of HTML transformation is moved from server-side to client-side — if your servers have less work with one request, they can handle more requests
- Richer UI – there are tones of jQuery plugins which you can use to improve user experience.

