Checkbox list Asp.Net view

Last year while working on a project, I encountered with a requirement about allowing users to select multiple options for a particular question. This was one of the requirements in most of the pages we planned to develop. Also second part of requirement is to make it generic so that there is no dependency on development team for further maintenance.

There was no such control available in Asp. Net which will resolve this issue. Alternatively, we need to create and extended control using HTML extensions and use it across all pages in web application.

This post doesn’t focus on introducing how to create HTML extension controls instead it presents an idea to implement such controls.

Couple of features of this control are, data can be driven by xml in app data folder. This will be read into memory during application start. There are few configuration items accepted as parameters to method to will define how many columns or rows user wants to see on the UI.

Now moving on to defining control. Any HTML extension need to be defined as a static partial class. once you have class defined, an extension method need to be declared. All extensions methods will have “this” as first parameter.

class declaration

Define member variables to hold values passed from UI. Like, options read from xml and other configurable items like whether control is editable, what will be the title, number of columns and any style information.

membervariables

Build html for the check box control in a look based on number rows. in this method we will be building a span tag. One of the parameter method declaration is position. This defines position of title field.

build html

Now handle number of html table based on number rows. Initially we calculated number of rows based on number of columns.

buildtable

Once control is defined with the namespace, this can be used similar to any other control in MVC view. for example “TextBoxFor”.

One Limitation of this control is information is stored in string array on the model. And in data base it will be as a comma separated string. There were methods written to convert comma separated string to string array and vice versa.