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

JSON Serialization using the DataContractJsonSerializer and C#

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

Download source code

Previously I’d done JSON serialization using the JavaScriptSerializer which is part of AJAX Extensions 1.0, but this is now obsolete.

.NET 3.5 introduced the DataContractJsonSerializer class.  The class sits in the System.Runtime.Serialization.Json namespace which is curiously hidden away in the System.ServiceModel.Web assembly.

The DataContractJsonSerializer can serialize a class that contains the Serializable attribute or any class defined as a DataContract.

Read more

JavaScript inline if statement

Posted on by Joe in JavaScript | Leave a comment

The JavaScript inline if statement is identical to the one in C#:

var forename = (gender == 'male') ? 'Joe' : 'Emily';

Escape curly braces when using String.Format or StringBuilder.AppendFormat

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

I was using the StringBuilder to create a JSON string which included an array and therefore curly braces, but I got an exception as curly braces are used to define the parameters for the format.

sb.AppendFormat("{\"Forename\":\"{0}\",\"Surname\":\"{1}\"}", person.Forename, person.Surname);

At first I tried adding a backslash which is used to escape the quotation mark but this didn’t work, so I tried the double character trick but adding two curly braces which seems to do the job.

sb.AppendFormat("{{\"Forename\":\"{0}\",\"Surname\":\"{1}\"}}", person.Forename, person.Surname);

Using the CustomValidator’s ClientValidationFunction

Posted on by Joe in ASP.NET, C#, JavaScript | 3 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"
                CausesValidation="false"
                OnClientClick="if (typeof(Page_ClientValidate) == 'function') { Page_ClientValidate(); if(Page_IsValid) { return confirm('You are sure?'); } };"
                runat="server"
                onclick="btnSubmit_Click">

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:

OnBeforeUnload

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:"; }
</script>

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.

Disable enter submitting form with JavaScript

Posted on by Joe in JavaScript | Leave a comment

On a project I was working on I was asked to disable the enter key submitting the form.  Usually it would be better just to ensure that hitting enter performed the correct action but if you do want to disable this you can do so with JavaScript.

I created a JavaScript function called disableEnterSubmit which takes in the event as a parameter as shown below.

function disableEnterSubmit(e)
{
    if (e.keyCode)
       return (e.keyCode != 13); //IE
    else
        return (e.which != 13); //FireFox
}

The event has different properties for the code of the pressed key for Internet Explorer and FireFox. In Internet Explorer we use e.keyCode and for FireFox it’s e.which.  The function simply returns false if the key is enter (key code 13).

I then just need to set the onkeydown event in the body tag of my HTML to call the method.

<body onkeydown="return disableEnterSubmit(event)">