Choosing a Game Development Framework

Lately I’ve had an idea for a game that I just can’t get out of my head.  Combined with the recent unveiling of the Nintendo Web Framework I’m compelled to make an attempt to get a demo of the game running on the Wii U.  At a recent presentation from Unite ’13, Nintendo touted how easy game development is for the Wii U using JavaScript and HTML5.  I’ve always wanted to explore the limitations of HD gaming within the browser so this is the perfect opportunity to test Nintendo’s claims.

Our weakness as developers is that when we have an idea we just want to code.  I don’t want to plan or design, I want to get something up and running and see the fruits of my labor as soon as possible.  As much as I love technology, some times I’m so compelled to code that I don’t even want to vet the best framework for the job.  Sometimes I’ll just grab what I’m most familiar with and start working.  With game development, that is difficult to do.

I wrote a previous post about the pitfalls of game development in JavaScript where I mentioned not reinventing the wheel.  I see so many horror stories of indie developers spending all of their time on an engine and not ever making a game.  I suggested a couple of frameworks in that post, but now that I’ve completed a more extensive vetting process I’d like to share some insight on the decisions that I made.

2D vs. 3D

If you are planning on making a 3D game, you should look no further than Unity.  You can quickly get prototypes of your game running by relying on Unity as a backbone.  There are a number of resources already available that you can take advantage of for development.  These include 3D models, plugins and tutorials for your project.

If you insist against Unity, CryEngine, Unreal Engine and the Source Engine are other options, but aren’t exactly targeted to indie developers.

I was dead set on making a 2D game; many aspects of my game rely on it.  Making a true 2D game in Unity is just not possible.  You can create a game with a fixed camera that limits movement to two dimensions but ultimately the assets and game will run 3D.  My inexperience with 3D game development had me a bit nervous going that route.

Web, Mobile or dare I say it…consoles?

I mention above that I already had some interest in the Nintendo Web Framework as a potential target, so the decision to make the game using JavaScript and HTML5 was practically made for me.  However, that wouldn’t make for a very interesting post now would it?

If I wanted to make a game for mobile platforms and perhaps PC/Mac/Linux, my previous experience would lead me to look toward cocos2d.  I have previously worked with cocos2d-iphone and found it easy to work with.  cocos2d-x is essentially the cross platform version of cocos2d, which has support for those and many other platforms.

Whittling It Down

A quick Google search turns up many JavaScript game development frameworks.  How do you decide which one to use?  I ended up filtering out options based on features that I saw as valuable to me.  This is obviously a subjective process, so your criteria may lead you to a different result than mine.

First, I needed something free and open source if possible.  I would hardly even consider myself an indie developer and I really can’t see myself financially contributing to a pet project like this.  Second, I’d prefer a framework that can work out of the box with standard tools such as Tiled for tile based map creation.

At this point I had narrowed my decision down to two options: cocos2d-html5 and melonJS.  It is going to sound odd based on my recommendation of cocos2d above, but after working with both options I eventually settled on using melonJS.  cocos2d has its applications but for lightweight, simple JavaScript game development it is my opinion that melonJS is the best framework out there.

Thanks to the great documentation, I had a simple platformer up and running using the melonJS boilerplate project within an hour of getting started.  I have yet to thoroughly stress test, but I’ve had no hiccups running the game at 720p within Chrome.

Why did I turn away from cocos2d-html5?  After some exploration it just didn’t seem like the best way to go for a lightweight JavaScript game.  Ultimately, cocos2d-html5 is meant for cross platform games between the web and iPhone, and the API reflects that.  I wanted something built for JavaScript from the ground up.

Have you been working with a framework that you really like?  Leave a comment to let me know.


Code Wars: Training in Programming Arts

As developers we have to frequently consult outside resources for information on how to complete certain tasks.  Whether it’s a book or an online tutorial, a quick refresher is always helpful to get a push in the right direction.  The problem is that we will often look for these resources when we know specifically what we need to do, rather than using them to buff up our skills.

There are many sites out there that allow you to do programming challenges to work on your proficiency with a language.  Project Euler, TopCoder or the Daily Programmer subreddit come to mind.  My newest addiction of this type of site is Code Wars.

What is Code Wars?

I like to explain Code Wars as a combination of small programming challenges and Xbox style achievements.  You complete a series of code “katas“: short snippets or bug fixes that test basic understanding of programming language concepts.  For each kata that you complete, you work your way up to higher ranks and increasingly more difficult tasks.

Code Wars Dashboard

The user dashboard in Code Wars.

Code Wars tracks the type of the katas that you complete into different types, such as bug fixes, algorithms and reference.  You can also complete katas in either JavaScript, Coffee Script or Ruby.  Since Code Wars starts with the basics, it is perfect for supplementing your learning of a new language.

Test Your Might

Code Wars provides you with a very simple code editor with syntax highlighting.  It works surprisingly well in the browser, complete with handling of indentation and other features.  You are also provided with the ability to write unit tests against your solution to test any cases that will help you complete the kata.  Then you submit your solution.  There becomes nothing more addicting than getting that green check mark every time you complete a kata.

The best feature of Code Wars comes after you complete a kata.  Once you submit your solution and it is verified, you get to see the solutions that other developers submitted as well.  Sometimes you will see solutions that are more complicated than your own, but quite often you will see solutions that are mind blowing in their simplicity.  I typically spend just as much time reviewing other’s solutions as I do coming up with my own.

Future Wars

I have no doubt that in the future Code Wars will bring support for more languages.  I’m excited at the possibility of completing code katas with Python or PHP.  I can’t help but think that Code Wars would also be an amazing tool for teaching people how to use the UNIX command line.

The beauty of Code Wars is that its katas are populated by user submissions, so it will continue to grow with new content in the as time goes on.

Want to test your skills?  Sign up by completing the example kata at!  Thanks for reading!  If you would like, you can view my Code Wars profile here!

Getting Started with the Stripes Framework

Stripes is an up-and-coming alternative to Apache Struts for developing web applications using Java. Stripes is very well documented, but leaves something to be desired in their sample projects and jump start information.  I’ve also noticed that while some of the features of Stripes are very extensible, it can be hard to understand what is needed and what isn’t.  I’ve included a quick briefing on some of the common pitfalls below.


ActionResolver is a component of Stripes that discovers your ActionBeans and maps them to URLs for you to use in your views. One common mistake that occurs when setting up a new Stripes project is not having the ActionResolver properly mapped to the package containing your ActionBeans. This is done in the web.xml configuration file for your project.

	<display-name>Stripes Filter</display-name>
		<param-value>{Your ActionBean package name goes here.}</param-value>

If this is not configured properly, you may see errors such as this: “Could not locate an ActionBean that was bound to the URL. Commons reasons for this include mis-matched URLs and forgetting to implement ActionBean in your class.” This can be misleading because the actual cause is related to neither of those reasons.


One particular difficulty that I had when I started working with Stripes was the usage of UrlBinding annotations. The reason for this is that if your ActionBeans are named properly, then you may never need to use them.

For example, let’s say you have an ActionBean class named LoginActionBean. By default, the ActionResolver will automatically bind this to the Login.action URL without any manual configuration required from you. The only time you ever need to use a UrlBinding is if your URL needs to differ from the automatically generated URL.

This is important to know, because at times the error messages returned by Stripes when it is not configured properly, such as the ones above, can lead you to using a UrlBinding even when you don’t need it.

Using HTML5/Custom Attributes

If you try to use custom attributes with one of the Stripes jump start projects, you will find that using HTML5 or other custom attributes will cause an exception to occur in Stripes.

For example, if you want to add an HTML5 placeholder attribute to a text input that is generated by Stripes, you will not be able to do it with the standard Stripes tag library.  This is also the case with JavaScript event attributes such as “onclick” or “onchange”, and custom attributes prefixed with “data-“.

I found the solution difficult to track down, but all you need to do is use the dynamic tag library provided with Stripes.  To use the Stripes dynamic tag library in your project, just add this taglib reference to the top of your JSP file:

<%@ taglib prefix="stripes" uri="" %>

You can use the standard Stripes tag library and the dynamic tag library together on the same page.  You just need to set the prefix value in the code above to something different than the prefix value you are using for the standard tag library.  This is actually the recommended usage of the dynamic tags, yet it is not used in any of the current Stripes samples.

Never fear

Stripes is a lightweight framework that is great for developing Java web applications. Not many people are using it, and unfortunately that means that there are not many resources available outside of the documentation. However, the documentation is very detailed and technical. The process of getting up to speed may take longer than usual, but having an alternative framework to available is great for the future of Java on the web.

More information, including samples and comparisons to Struts can be found at

System.Web.WebPages conflict between ASP.NET MVC 3 and ASP.NET MVC 4

After installing ASP.NET MVC 4, you may notice that you are unable to load projects that used previous versions of ASP.NET MVC. You may see an error similar to the following:

The type ‘System.Web.Mvc.ModelClientValidationRule’ exists in both ‘c:\Program Files (x86)\Microsoft ASP.NET\ASP.NET MVC 3\Assemblies\System.Web.Mvc.dll’ and ‘c:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v2.0\Assemblies\System.Web.WebPages.dll’

This error occurs because prior to MVC 4, projects did not specify which version of ASP.NET Web Pages to use, since there was only one. Luckily, the fix for this is as simple as updating the project file to the proper reference of System.Web.WebPages. Many developers have not ever needed to modify a project file directly, since the default Visual Studio configuration is often sufficient. This can make editing a project file an intimidating task, so I have assembled detailed steps to solve the problem.

From the Solution Explorer, right click on the project and click “Unload Project” from the context menu.

The "Unload Project" menu item in Visual Studio 2010.

The “Unload Project” menu item in Visual Studio 2010.

You should see that the project is now marked with (unavailable). Right click on the project again and you should be able to select a new item, “Edit {Your Project Name}.csproj”. The extension will be displayed as .vbproj for VB.NET projects.

The "Edit Project" menu item in Visual Studio 2010.

The “Edit Project” menu item in Visual Studio 2010.

An XML configuration file will open. This contains all of the information that tells Visual Studio how to run your project. Scroll down (or search the file) until you find the following line:

<Reference Include="System.Web.WebPages"/>

Replace that entire line with this:

<Reference Include="System.Web.WebPages, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"/>

Save the changes to the project file. Right click the project name in the Solution Explorer again. This time, select “Reload Project”. Your project will reopen in Visual Studio and should now build and run properly.

In simple terms, what we have done here is update the Reference tag to include version information, which resolves the conflict for Visual Studio.  It now knows which version of System.Web.WebPages you intend to use for your project.

Thanks for reading.  Still having trouble resolving the error?  Feel free to leave me a comment below!

From the Bookmarks Bar – July 12, 2013

I’m going to give something new a shot here.  From the Bookmarks Bar is a weekly round-up of interesting software development related links from around the web.  In general, it’s just a collection of things that I think you may find interesting.  Without further ado, here some favorites From the Bookmarks Bar for this week:

New Programming Jargon

We’ve all run into these issues from time to time.  This article reads like a book of the best programming related jokes.  Smurf Naming Convention is my favorite.

Raspberry Pi Powered Microwave

Disappointed by the lack of features on your microwave?  Why not overhaul it by integrating a Raspberry Pi?

The Visitor Pattern Explained

Many developers have only a brief understanding of the visitor pattern even after using it.  This is a detailed and practical example of the usage and practices of the visitor pattern.

How to Modify Bootstrap Simply and Effectively

Here is a collection of some great Bootstrap mods as well as some tools to easily modify Bootstrap to your tastes.  Want to make your Bootstrap based site look like Facebook or Metro in Windows?  An add-on can make it happen.

Super Mario Bros. 3 Match Game in Javascript

This is a fun one.  A developer has built a slick recreation of the match game from Super Mario Bros. 3, written entirely in JavaScript.  The project is well segmented and structured and is a good example for those looking to learn modern JS.  Source code is available here:

That’s it for this week.  I’ll be experimenting with From the Bookmarks Bar over the next couple of weeks.  Feel free to leave a comment and let me know what you think.  Thanks for reading!

Dynamic Font Size (and other styles) in an Android App

I was recently tasked with adding the ability to change font size globally through the user’s selection in the application settings panel. Android provides accessibility settings on the device level that allow you change the font size for all apps on the device. This is made easy to implement in your app through built-in structures in Android, but documentation is not specific on the most efficient way implement this on an application level. This is likely to be because it is not an encouraged practice, but in my particular case, the requirements were that this needed to be changed in the settings for the application since more options would be available than the standard usability features of Android provide.


The key to storing settings in an Android application is SharedPreferences. The examples below do not demonstrate how to write values using the SharedPreferences editor, just how to retrieve them. For more information on writing to SharedPreferences, see this article.

The case against subclassing TextView

Do a quick Google search on implementing a global font size in code and you’ll see many responses suggest to subclass TextView and load the text size options there. Then all you have to do is make sure you use this class for every TextView in your layout. Simple enough, right? Will this work? Absolutely. Is this option going to cause more trouble than its worth as development on your app becomes more complex? Definitely.

The problem here is that many of the Android widgets subclass TextView, such as Button, RadioButton, and CheckBox. Some of these are indirect subclasses of TextView, which makes implementing your version of TextView in these classes a pain. Not to mention the trouble that could arise from migrating to newer versions of Android in the future.

Styles vs. Theming

As you may already know, you set styles for your layouts to control the look and feel of the view. Themes are essentially just collections of these styles. Theming can often be ignored by developers because it is seen more as a method for controlling collections of styles and not just a single style like text size. Many developers think, “I like the default Android theme, so I don’t need to worry about configuring themes.” However, you can use a theme just for text size settings; they don’t need define values for every property. Using a theme over styles provides us with one huge advantage: we can set a theme for the entire view programmatically. Without this, we would have to traverse the tree of children in the view and set each style using the associated property. With multiple properties to change and multiple nested child views, this can get complicated.


First, we need to define the settings in our themes.xml file. This file normally resides in the “res/layout” folder within your application. If it does not exist, you can create it. Here I only use options of Small, Medium and Large, but we could easily add many other options here if necessary. Here is an example:

	<style name="FontSizeSmall">
		<item name="android:textSize">12sp</item>
	<style name="FontSizeMedium">
		<item name="android:textSize">16sp</item>
	<style name="FontSizeLarge">
		<item name="android:textSize">20sp</item>

Then we will create a class to handle loading our preferences. I called it FontSizeActivity, you could call it ThemedActivity if you are setting more values than just the font size.

public class FontSizeActivity extends Activity {
	public void onStart() {

		// Enclose everything in a try block so we can just
		// use the default view if anything goes wrong.
		try {
			// Get the font size value from SharedPreferences.
			SharedPreferences settings =
				getSharedPreferences("com.example.YourAppPackage", Context.MODE_PRIVATE);

			// Get the font size option.  We use "FONT_SIZE" as the key.
			// Make sure to use this key when you set the value in SharedPreferences.
			// We specify "Medium" as the default value, if it does not exist.
			String fontSizePref = settings.getString("FONT_SIZE", "Medium");

			// Select the proper theme ID.
			// These will correspond to your theme names as defined in themes.xml.
			int themeID =;
			if (fontSizePref == "Small") {
				themeID =;
			else if (fontSizePref == "Large") {
				themeID =;

			// Set the theme for the activity.
		catch (Exception ex) {

Finally, we extend our existing Activity classes with the new FontSizeActivity, like this:

public class AppActivity extends FontSizeActivity {


Yes, I know. I plead the case against subclassing TextView and then I ended up subclassing Activity for my example. What gives? Think of it this way; you should have a much fewer amount of Activities in your application than you do TextViews or widgets that inherit TextView. This will be exponentially so as complexity increases, so this solution requires less changes in code for you. In addition, the built-in subclasses of Activity are much less commonly used than the subclasses of TextView. You will need to extend those activities as well, but again they will ultimately require less code.


I’ve fought with all of the other ways to allow style based settings in Android and none of them have even come close to being this easy to implement. It is important to consider future changes to your application and this solution handily beats the other options in that regard. Thanks for reading.

An in depth look at ASP.NET MVC’s TempData

Ask around about using TempData in ASP.NET MVC and you’ll get plenty of opinions, but few answers to real questions. “It’s contrary to the MVC pattern,” the more respectful responses will say, others will simply “answer” your question with, “Just don’t use it.” It can be a frustrating wall to encounter when you are simply looking for information to evaluate it as an option for your application or when you need to support code that already uses it.

Few technologies actually deserve that “do not use” label for all situations. The amount of technology elitism that is spread around forums and the internet is staggering. As developers, we have all found small applications for less commonly used technology, even if it is just that sparingly used script or internal web site. There are pros and cons to every technology, and any developer worth their weight in dirt should be able to recognize that.

So, OK, end rant. The point is that despite internet opinion, there are some valid uses for TempData. A wizard based process comes to mind. There are times when you just don’t want to post unused data back to the server every time. It’s a cumbersome process and leaves you responsible for validating what comes back from the client every time, whether you’ve already validated it or not.

What is TempData?

TempData is essentially managed session storage. ASP.NET persists your objects on the session between a single request and then removes them afterward, unless you say otherwise. See the code snippet below for a quick sample:

public ActionResult WizardStep1(WizardStep1Model model)
     if (ModelState.IsValid)
          TempData["Step1"] = model;
          // OR TempData.Add("Step1", model); works fine as well.
          return RedirectToAction("WizardStep2");

     return View(model);

In the WizardStep1 action, we save the model from step 1 to TempData if it is valid, and then we move on to step 2. TempData is essentially a dictionary with a key of string and a value of object, so we can use most of the methods that we would normally use for a Dictionary.

Retreving from and keeping TempData

Let’s consider a three step wizard process. Step 1 is as shown above. We start getting data from the user and move on to Step 2. During Step 2, we gather even more data and move on to step 3 where we (finally!) save everything to the database.

In order to get our data from steps 1 through 3 (cue Brian McKnight), we will need some mechanism to keep the data from step 1 while also adding the data from step 2, since it is only persisted for one request. This is where the Keep method comes in.

public ActionResult WizardStep2(WizardStep2Model model)
     // We use the same key from when we set the data to get it back...
     WizardStep1Model step1 = (WizardStep1Model)TempData["Step1"];
     // BUT, we can also use ContainsKey or TryGetValue in cases
     // where the data might be null...
     if (step1 == null)
          // The user may have skipped step 1, so we go back.	
          // We could save the step 2 data to TempData if we wanted to.
          return RedirectToAction("WizardStep1");

     // We need to tell TempData to keep the Step 1 model for one more request.<br />	
     if (ModelState.IsValid)
          // And, if Step 2 is valid, we'll save it as well.	
          TempData["Step2"] = model;	
          return RedirectToAction("WizardStep3");

     return View(model);

We’ll need to keep the data for Step 1 whether the Step 2 model is valid or not, so we do that outside of the if block for ModelState.IsValid.

It is important to note that TempData only persists for one request. The following GET request following the RedirectToAction qualifies as a request. This means that in the get method for each step, we need to keep the TempData so it is there when we post back. Here is how this would work on the redirect to Step 3.

public ActionResult WizardStep3()
     return View();

Notice on the call to TempData.Keep in WizardStep2 that we provided the key that we used to store the Step 1 data to TempData. That marks only that object for retention in TempData, meaning that all others that are not marked will be disposed. In WizardStep3, we have both Step 1 and Step 2’s data in TempData. We can call TempData.Keep with no parameters to mark all objects in TempData for retention.

When we post to WizardStep3, we can retreive both Step 1 and Step 2’s data from TempData, using a similar method to Step 2. There we can save them all to a database at the same time using Entity Framework or any other database persistence.

Why TempData over Session?

You can see from the example above that once the user is finished with the wizard process, that we will no longer need the data from those forms. If you were to save this data to the session, it would stay there until you removed it manually, abandoned the session, or the session expired. Like TempData, the session has its benefits, but in this case it is easier to tell TempData on the off chance that we need to keep the data, rather than to always tell the session to get rid of it.


The truth is that many of the complaints about TempData are valid. It is a loophole outside of the MVC pattern and it is a volatile approach to persisting data. The problem is that despite the views of many opinionated developers, no one pattern is the solution to every problem. If anything else, I hope you have the information to decide whether using TempData is right for you.

Thanks for reading. Feel free to leave any questions or comments.

Managing an SQLite database on an Android Virtual Device

Mobile database development is often an unfamiliar when coming from the world of web development. Many database administrators are used to managing their databases through a management tool such as SQL Server Management Studio, phpMyAdmin or MySQL Workbench. They can feel a bit out of place when they find themselves creating SQLite databases by writing queries in Java or Objective-C code. Sometimes having a visual representation of the data just helps with understanding a system and can speed up development.

So, how can I directly manage an SQLite file?

When running an Android application on an actual device, we always have access to the file system over USB, so we can just download the SQLite database to our machine and manage it from there. In addition, there are many SQLite browser applications available for Android, such as SQLite Manager and SQLite Viewer, that allow you to browse the contents of an SQLite database directly from your device.

Note: The SQLite database for your application will always be found in the data -> data -> {application package name} -> databases folder on the Android file system.

The problem is that many developers do not develop on an actual Android device, at least not in the early stages. Instead, they run their application on the Android Virtual Device through the Android Developer Tools or Eclipse. While it is a bit more complicated, you can also download your application’s SQLite database from a virtual device. Here’s how it’s done:

Before following the steps below, make sure that your Android Virtual Device is running and connected to Android Developer Tools. Also, make sure that your application has successfully created an SQLite database on the file system.

1. Open the DDMS perspective in ADT by clicking the DDMS button in the top right hand corner of the application. You may only see the “Java” and “Debug” perspectives initially. If that is the case, you will need to click the open perspective button and choose “Other…” from the menu. From the next screen, choose DDMS and click OK.


The “Open Perspective” button in ADT.

The "Open Perspective" dialog in ADT with DDMS highlighted.

The “Open Perspective” dialog in ADT with DDMS highlighted.

2. You should see your AVD information in the left hand pane. In the right hand pane, choose the File Explorer tab.

3. From the file tree, expand to the data -> data -> {application package name} -> databases folder where you should see your SQLite database.

4. Select the database file and click the “Pull a file from the device” button in the top right hand corner of the File Explorer pane. A save dialog should appear.

The DDMS File Browser with the "Pull a file from the device" button shown.

The DDMS File Browser with the “Pull a file from the device” button shown.

5. Choose a location to save the file on your local machine.

Once the files is on your local machine, you can use any SQLite management tool to browse and modify your database. SQLite Explorer is a great free, open-source option for those looking for a recommendation.

There is also a plug-in for Eclipse available that will handle the process of downloading and opening the database for you. It allows you to manage the database directly from Eclipse. You can download it here.

If you need to make a change to the database, you can do it through your management software, and use the “Push a file onto the device” button from the File Explorer to push the updated database to the virtual device.

This is a great method of seeing exactly what is going on with your database every step of the way. While unit testing is still a crucial part of making sure your application functions correctly, visualizing the data can help to quickly resolve obvious bugs.

Thanks for reading. Feel free to leave any questions or comments.

ASP.NET MVC Validation Messages using jQuery UI Tooltips

Traditionally in ASP.NET you add a single Validation Summary above your form that describes the errors that the user has made, or add validation messages next to each control in the form to grab the user’s attention to each particular field.  The example below from the default MVC 4 application illustrates this.

Default Validation Behavior

The default validation behavior in the ASP.NET MVC 4 internet application.

The problem comes when trying to format a form with a large number of fields in a way that is pleasing to the user and also does not use much space on the screen.  jQuery UI tooltips are an alternative option.  The user would see a general message that some errors have occurred on the form or a style change to indicate the fields that are problematic.  This could be a red border around the field, or even an asterisk.  When the user clicks that field to change the data, they are presented with the full error message in a tooltip.  It works well in limited space and it’s flashy!

What You Will Need

This particular walk through uses a strongly-typed Razor view in an ASP.NET MVC 4 project.  Specfically, the Login view from the default “Internet Application” project generated by Visual Studio.  MVC 3 will work fine as well.  If your project does not include jQuery UI, you will need that as well.  The default project does have jQuery UI already included, but not the tooltip libraries, so I just included the newest version from jQuery’s CDN.

Setting Up the Validator

Most commonly, forms in ASP.NET MVC use the Html.ValidationMessageFor method to generate a validation message based on the model field that is passed in.  This causes a problem with jQuery UI tooltips because the ValidationMessageFor method generates span elements and other HTML around the message for formatting purposes.  What we need to use here is the ValidateFor method, which will attach all of our validation data to the input field.  We can still set all of our information in the model as we usually do, but with out all of the extra HTML.  Here are my modifications to the User Name and Password fields to use the ValidateFor method.

     @Html.LabelFor(m => m.UserName)
     @Html.TextBoxFor(m => m.UserName)
     @{ Html.ValidateFor(m => m.UserName); }
     @Html.LabelFor(m => m.Password)
     @Html.PasswordFor(m => m.Password)
     @{ Html.ValidateFor(m => m.Password); }

One thing should jump out at you right away, and that  is the usage of the ValidateFor method on lines 4 and 9.  ValidateFor is a void method that has no return value, so we need to call it inside of a code block instead of directly like we call Html.TextBoxFor.  A semicolon is necessary as well to terminate the statement.

Adding on a jQuery UI Tooltip

Attaching the jQuery UI tooltip to the control is a piece of cake.  All you need to do is add this snippet of JavaScript to your log in page:

<script type="text/javascript">
    $(function () {
            items: ".input-validation-error",
            content: function () {
                return $(this).attr('data-val-required');

We attach the tooltip only to fields that have the “input-validation-error” class. This allows us to only show the error if there is something wrong with the data that the user has entered. If the data for a field is OK, the user will never see the tooltip.  Our custom content function grabs the “data-val-required” attribute from the input tag to display as the tooltip mesage, which contains the validation message that you set in your model.

Validation with jQuery UI Tooltip

Validation with jQuery UI Tooltip

Here’s our new and improved (and much more compact) log in form!  You can see that we have the red borders to tell us which fields need updating, but the tooltips will hide unless the user focuses on the field.  In this case, the password validation message will show when the user switches to that input, and the User Name validation will hide.

The possibilities for styling and positioning the tooltip with jQuery UI are endless.  For example, you could add a bright red alert box and you could position it anywhere in reference to the field; above, below, or to the side.

It’s really that easy.  Please feel free to leave a comment if you have any questions.

Avoid HTML Escaping in an ASP.NET MVC WebGrid Column Format

I ran into an issue with the new ASP.NET MVC WebGrid.  I had difficulty finding any information out there on a good way to do this, so I thought I would post my solution.  The WebGrid easily generates paged and sorted tables automatically. You can find more information on the ASP.NET MVC WebGrid here.  In my case, I am listing some data for the user and I want to show any new rows in bold to make it more noticeable. Adding any HTML tags to the format property as a string will result in the tags being escaped. See the following example:

        columns: grid.Columns(
            grid.Column("Text", format: (item) => item.New ? item.Text : "<strong>" + item.Text + "</strong>")

Notice that item.New is a Boolean value.  This results in the following encoded HTML output within the table cell:

<strong>Sample Item Text</strong>

Not exactly the intended effect.  However, if you pass in a new object of type MvcHtmlString with the string in its constructor:

        columns: grid.Columns(
            grid.Column("Text", format: (item) => item.New ? item.Text : new MvcHtmlString("<strong>" + item.Text + "</strong>"))

Voila!  This will result in the properly bolded text:

Sample Item Text

This method will work for any of the other Html Helpers as well, though my example specifically references WebGrid.  In other cases, the Html.Raw method can be used to print HTML, but inside of the grid column it will still be escaped.  I’ve tested multiple ways of adding the grid column format using “@:”, but none of the documented methods seem to work within a ternary operator.