Using KnockoutJS with SignalR in ASP.NET MVC

KnockoutJS is a MVVM implementation for JavaScript written by Steve Sanderson, in my opinion the author of the best ASP.NET MVC textbooks available. Simply put it lets you bind a JavaScript object model to your HTML UI using a Read more

A MongoDB Tutorial using C# and ASP.NET MVC

In this post I'm going to create a simple ASP.NET MVC website for a simple blog that uses MongoDB and the offical 10gen C# driver. MongoDB is no NOSQL database that stores information as Binary JSON (BSON) in documents. I Read more

Linq To SQL Tutorial

Check out some of my other Linq to SQL posts: EntityBase Inheritance Modifiers with SQLMetal Linq to SQL with WCF Services Linq to SQL Framework (Repository/Business wrapper) ObjectDataSource binding with server side paging and sorting Load Options Generic Framework using reflection This is a basic tutorial for Read more

Control.TryFindControl Extension Method

Posted on by Joe in ASP.NET, C# | Leave a comment

Following on from my last post creating an extension method to use FindControl recursively I thought it would be cool to also have a TryFindControl method which works in a similar way to Int32.TryParse which I use regularly.

Below is a generic extension method that uses my previously created recursive FindControl method to cast the object to the correct type if found and send it back as an out parameter, then return a boolean indicating if the control was found.

public static bool TryFindControl<T>(this Control ctrl, string id, out T control, bool recursive) where T : class
    Control ctrlFound = ctrl.FindControl(id, recursive);
    control = ctrlFound as T;
    return ctrlFound is T;

The method could then be used like so.

TextBox txt = null;
if (this.TryFindControl<TextBox>("txtName", out txt, true))
    txt.Text = "Joe Stevens";

Recursive FindControl Extension Method

Posted on by Joe in ASP.NET, C# | Leave a comment

When working with templated controls it’s quite common to need a recursive FindControl method to navigate down through the control hierarchy to find the control you want.

Here is a simple extension method I wrote for Control to do this:

public static Control FindControl(this Control ctrl, string id, bool recursive)
    if (recursive)
        foreach (Control child in ctrl.Controls)
            if (child.ID != null && child.ID.Equals(id))
                return child;

            if (child.Controls.Count > 0)
                Control found = FindControl(child, id, true);
                if (found != null)
                    return found;
        return ctrl.FindControl(id);

    return null;

CheckBoxList ListBox SelectedItems Extension Method

Posted on by Joe in ASP.NET, C# | Leave a comment

I’ve been working with the CheckBoxList control and it’s annoying there is no property to get the selected items.

I wrote a simple extension method for ListControl, the abstract class that CheckBoxList and ListBox derive from, to get the selected items:

public static ListItemCollection GetSelectedItems(this ListControl source)
    ListItemCollection selectedItems = new ListItemCollection();

    foreach (ListItem item in source.Items)
        if (item.Selected)

    return selectedItems;

I could loop through the selected items like so:

foreach (ListItem item in myCheckBoxList.GetSelectedItems())
    //Do something with the item

It would be even better if Microsoft implemented extension properties so that I can loose the parenthesis.

ObjectDataSource Exception Handling

Posted on by Joe in ASP.NET, C# | Leave a comment

I was using the ObjectDataSource today to display and delete data using a GridView.  When I tried to delete a record that was referenced in another table an exception was thrown due to referential integrity.

I found that in implementing the Deleted event of the ObjectDataSource, the ObjectDataSourceStatusEventArgs class had a boolean property called ExceptionHandled.  Setting this to true stops the ObjectDataSource from re-throwing the exception, allowing you to handle it yourself.  You can obtain the underlying exception using the Exception property.

protected void odsUser_Deleted(object sender, ObjectDataSourceStatusEventArgs e)
    if (e.Exception != null)
        e.ExceptionHandled = true;
        //Perform own exception handling
        lblError.Text = e.Exception.Message;

You could also use the same approach with the Updated event.

ASP.NET Property Parameter for Data Sources

Posted on by Joe in ASP.NET, C# | 3 Comments

A few years ago I wrote a custom parameter for data sources such as the ObjectDataSource which used the value of a property on the page for a parameter.

I needed this functionality again so I found what I had previously written and improved it to make it more usable.

Read more

Fill PDF Form Fields from an ASP.NET page using iTextSharp

Posted on by Joe in ASP.NET, C# | 2 Comments

Download the source code:

For a project I’m working on I needed to be able to generate PDF’s containing data from my page.  I came across a library called iTextSharp which is a C# port of the Java library iText.  Using this library allows you to generate PDF files on the fly.  You can download the library here, and need to add it as a reference in your project.

In Adobe Acrobat I created a rather crude looking PDF with two Form Fields for Forename and Surname, named txtForename and txtSurname respectively.

Read more

Using the CustomValidator’s ClientValidationFunction

Posted on by Joe in ASP.NET, C#, JavaScript | 2 Comments

The ASP.NET CustomValidator allows you to create custom validation that fits into its validation framework.  The CustomValidator has a server side event called OnServerValidate and a client side event called ClientValidationFunction.

You can use the CustomValidator by just implementing the OnServerValidate event, but any other validation controls that are validated client side will need to be valid before the CustomValidator will be used.  Doing this causes a postback to validate the CustomValidator and as it’s not client side the validation message will not be shown in a ValidationSummary.

Read more

Show a JavaScript confirm dialog box after client validation

Posted on by Joe in ASP.NET, C#, JavaScript | 7 Comments

It’s quite common to use a JavaScript confirm dialog on a button press to ensure that the user wants to submit the page.  If you are using any of the ASP.NET validators that use client side validation you will find the confirm appears before the validation, whereas it would be better if the confirm box only appeared if the page was valid.

Luckily the framework supplies some JavaScript functions that can be used for validation.  Page_IsValid is a boolean indicating if the page is valid which can be used in client script.  This value is set when the JavaScript function Page_ClientValidate is executed.

For this example I have set CausesValidation to false on the button that will show the confirm dialog, as I will call the client side function myself.  If I don’t to this my validation will be called twice.  In the OnClientClick I then need to add some JavaScript to call Page_ClientValidate if the function exists, and then only show the confirm dialog if Page_IsValid is true:

<asp:LinkButton ID="btnSubmit"
                OnClientClick="if (typeof(Page_ClientValidate) == 'function') { Page_ClientValidate(); if(Page_IsValid) { return confirm('You are sure?'); } };"

Generate a CSV from a generic list of objects using reflection and extension methods

Posted on by Joe in ASP.NET, C# | 12 Comments

Download the source code for this post:

Last week I wrote a post about generating a CSV from a DataTable. As I hardly use DataTables these days I thought it would be good to write a function that does this for a generic list of objects using reflection to get the properties of the object and export them.

In this example I have done this using an extension method on the generic list. This approach could also be easily applied to the DataTable example.

Read more

Show ‘Are you sure you want to navigate away from this page’ message like Hotmail

Posted on by Joe in ASP.NET, JavaScript | 2 Comments

If you start typing an email in Hotmail then navigate away without saving or sending it you get the following message:


This is done by using the onbeforeunload window event.  This event can be used to perform any processing needed before navigating to a new page, but if the event handler returns a string you get this confirmation dialog with your own string replacing “You haven’t sent this message. Are you sure you wan’t to discard it?“.  If you press OK then the navigation continues, and if you press Cancel then you remain on the same page.

Here is an example of how to use the event:

<script language="javascript" type="text/javascript">
    window.onbeforeunload = function() { return "Your message here:"; }

This could come in useful if you had a form on your page, and you don’t want the user to accidentally navigate away from the page and loose what they have entered.