Archive for category C#

How to build a Check Box Group Helper with ASP.Net MVC 2.0

ASP.Net MVC 2.0 comes with great HTML helpers right out of the box, which include a check box helper. Unfortunately the way in which the check box helper renders a check box is not the traditional way most web developers use check boxes. Microsoft instead went with a true/false scenario for check boxes, which is great for many uses of check boxes. However, it does not support a named group of check boxes that many web developer’s use.

What We Want

So with that in mind we’re going to create a MVC Check Box Group Helper.

First let’s look at what the well formed html for the check box group with labels looks like:

[code lang="html"]






[/code]

Obviously the check box group is for selecting colors and the values are hex color codes.

The check box group name is “Colors”; each check box has a unique value and a unique ID. The unique ID allows you to use the labels “for” attribute to specify which check box it is for, thus when you click on an associated label it toggles the check box.

Constraints

Now for some constraints for the check box group:

  • Easy to use
  • Maps to an IEnumerable
  • Does not use JavaScript
  • Does not use hidden form elements
  • If possible reuse preexisting MVC classes

All of these are pretty straight forward and will come into play as we design this.

If you’re not aware Microsoft released MVC’s source code under the MS-PL open source license. This is great as it lets us peak under the hood and see how they implement things. This is really great if you want to make your own helpers and take into consideration things that the official helpers do as well.

The Foundation

Since a check box group will obviously need some data it will need some sort of container which can represent a check box. It will need to keep track of just a few things:

  • The text to display
  • A value to use
  • And if it’s checked

In fact, just like SelectListItem. Here’s the source from the MVC project for SelectListItem.

[code lang="C#"]
namespace System.Web.Mvc {

public class SelectListItem {

public bool Selected {
get;
set;
}

public string Text {
get;
set;
}

public string Value {
get;
set;
}
}
}
[/code]

It can’t be much simpler than that, and as it turns out we can make use of this perfectly for our check box. With SelectListItem we can either use SelectList or IEnumerable<SelectListItem> to keep our list.

With that out of the way we now have something to hold the data for our check boxes in that is easy to translate our own data into, people are familiar with it already, and it satisfies our fourth constraint.

The Helper

Okay, now for our helper. If you’re not familiar with how to create a basic helper with extension methods you can read this great article and then come back here.

Let’s look at the constructor of our new helper whose parameters are quite simple.

[code lang="C#"]
public static string CheckBoxGroup(this HtmlHelper htmlHelper, string name, IEnumerable selectList)
[/code]

And you’ll use it in your view like so:

[code lang="asp"]
<%= Html.CheckBoxGroup("Colors", Model.Colors) %>
[/code]

As you can see, the name of the group will be “Colors” and I’m passing an IEnumerable<Color> from my View’s model (you’re using strongly typed views right?).

Now here’s the actual helper code:

[code lang="C#"]
public static string CheckBoxGroup(this HtmlHelper htmlHelper, string name, IEnumerable selectList)
{
name = htmlHelper.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(name);
if (string.IsNullOrEmpty(name))
{
throw new ArgumentException("Parameter must be specified.", "name");
}

StringBuilder listItemBuilder = new StringBuilder();

int count = 0;
foreach (SelectListItem item in selectList)
{
listItemBuilder.AppendLine(ListItemToCheckBox(item, name, count) + ListItemToLabel(item, name, count) + "
");
count++;
}

return listItemBuilder.ToString();
}
[/code]

This is obviously modeled after the Drop Down List helper that comes with MVC.

The guts of the helper come down to the for loop. For each of the select list items we’re building a line of HTML that includes both our check box and our label. The code for which is here:

[code lang="C#"]
internal static string ListItemToCheckBox(SelectListItem item, string name, int count)
{
TagBuilder builder = new TagBuilder("input");

builder.Attributes["type"] = "checkbox";
builder.Attributes["name"] = name;
builder.Attributes["id"] = name + count;

if (item.Value != null)
{
builder.Attributes["value"] = item.Value;
}
if (item.Selected)
{
builder.Attributes["checked"] = "checked";
}
return builder.ToString(TagRenderMode.Normal);
}

internal static string ListItemToLabel(SelectListItem item, string name, int count)
{
TagBuilder builder = new TagBuilder("label")
{
InnerHtml = item.Text
};

builder.Attributes["for"] = name + count;

return builder.ToString(TagRenderMode.Normal);
}
[/code]

And there you have it. Put the constructor and the two internal static methods in a class and you have a Html.CheckBoxGroup helper.

What Next?

There is room for improvement on this model. I didn’t handle everything, if you want to expand it some things I’ve done or looked into are:

  • Custom HTML Attributes
  • More customization on how check boxes are separated
  • Creating a Strongly Typed version

Using Table-Valued Parameters in SQL Server 2008 and C#

Until recently I had not had an opportunity to use Table-Valued Parameters a new feature in SQL Server 2008. I had looked at them briefly, thought they were a nice addition, and then moved on. Finally though, I found a chance to use them.

The intended use for Table-Valued Parameters is of course to send multiple rows of data to SQL Server from the client. Previous ways to do this involved calling a single stored procedure repeatedly, using XML, using SQLBulkCopy, or my least favorite, creating a stored procedure with many parameters. Each of these methods had draw backs. Calling a single stored procedure over and over works just fine (and was my preferred method) but you are creating a lot of traffic for something that should be simple. XML was nice too, but depending on the complexity of what you are sending you will need a lot of XQuery in your stored procedure; making something simple much more complex. SQLBulkCopy works great, I’ve used it before, but sometimes you may want to do more to your data once it is at the database. Thankfully table-valued parameters solve many of these short comings.

You can use table-valued parameters from your application with DataTables, DbDataReader, or IEnumerable objects. The majority of examples for table-valued parameters are done using DataTables. The problem I have with DataTables is that this seems like too much of an ad-hoc method with more overhead then is needed. Whereas going the IEnumerable route lets you create and use objects that you would likely already be using. This is the route I prefer, and the one I will demonstrate.

For this example assume we have a database of people and each of the people may have one or more aliases. They must be rather shady people. Here is the table for storing the people:

It is quite simple, an identity field called ID to give everyone a unique number and a first and last name.

Now we have a table to store their aliases:

Another simple table to keep our shady people’s aliases; let’s pretend for ease of use there are primary keys and foreign keys shall we?

To add to this table we will use a stored procedure, my favorite mechanism to get data to the database. Why? Because you give the DBA something concrete upon which they can optimize your database, among other reasons. But that’s another post.

Our stored procedure will be an inserting stored procedure which will add our new shady person and their aliases in one call. Thus we will need to create our user-defined table type  first.

Again, nothing complicated. You will see why I left off the ID field in a bit.

You should note that you cannot use ALTER commands on user-defined table types. So if you want to update the table type later you will have drop it and create it. But if it is being used by a stored procedure you will have to temporarily comment that out of your stored procedure first, then drop the UDT, create the UDT again, and uncomment the UDT in your stored procedure. So plan ahead! Having planned ahead, here is our stored procedure for inserting:

The stored procedure requires three parameters: a first name, a last name and the user-defined table-valued parameter. The table type must be marked as READONLY and thus you will not be able to update the table within the stored procedure, only select from it. Otherwise, the stored procedure is rather straight forward. The person is added to tbl_Person and the aliases are added to tbl_Alias. You can see why I chose not to have the ID part of the user-defined table type, since we will not the ID till the person has been inserted.

To use the stored procedure in SQL Server Management Studio you can do the following.

The output should look like this.

Output

Output

Great, we’re halfway there! The database side of things is taken care of, now we will need to take care of our client. Within the client code we will create a Person class. The class will have a property for the first name, last name, and aliases. This is why I like the IEnumerable route; it makes sense to store the aliases for a person with the person, and doing so as a list makes sense.

Person Class:

Alias Class:

AliasCollection Class:

Let’s look over this code. First off the Person class has three public properties. FirstName, LastName, and Aliases. The Aliases property is an instance of the AliasCollection class, which inherits the Alias class as a List and then implements the IEnumerable interface. The List<Alias> turns our Alias into a List, which is perfect for handling our aliases within the client code.

The implementation IEnumerable<SqlDataRecord> is what will let us use our List as the input to our user-defined table. Specifically we are implementing IEnumerable with SqlDataRecord, this represents a single row of data and its associated metadata. This is what ADO.Net and SQL Server will need to map our list of aliases to our user-defined table. The documentation is not really clear on this part unfortunately, it leads you to believe that anything that implements IEnumerable should suffice, however; what you must have is IEnumerable with SqlDataReader. This does not come out of the box with List<Alias> so we create our own, otherwise we’ll get an InvalidCastException.

Finally, from our client, using the Enterprise Library Data Access, we can load people and aliases using a user-defined table type.

I know personally, I’ll be using this method from now one whenever possible over using user-defined tables with ad-hoc DataTables to load data, or heaven forbid calling the same stored procedure repeatedly.

Tags: ,