ASP.NET MVC: Implementing CheckBoxList

My events site I’m building ASP.NET MVC got tags support for events. I implemented CheckBoxList helper method and tag updater method that I can use to update tags assigned to events. In this posting I will show you how to implement tags support using CheckBoxList helper in ASP.NET MVC.

About my solution

Event and tags modelMy event and tag object are shown on image on right. It’s the same system I used as example in my blog posting about implementing tagging support in ASP.NET MVC applications. Between events and tags there is many-to-many relationship. Because table between events and tags has composite primary key that is made of event ID and tag ID (no more fields) it is not mapped as object by Entity Framework but as many-to-many relationship between events and tags.

My admin interface is right now generated by using controllers scaffolding with Entity Framework data model. It is simple, minimal and primitive (and a little bit disturbing). I needed a way to assign tags to events through admin interface. On ASP.NET Forms we have checkbox list available. In MVC we have nothing built-in. So I implemented something using materials I found form web.

Implementing CheckBoxList

As a first thing let’s make CheckBoxList work. There is very good solution offered by Jeremiah Clark in his blog posting CheckBoxList Helper for MVC. I have a little bit modified version of it – partly written and before and partly after I found Jeremiah’s solution. I will polish it later if I have tried this extension method on more than one entity tagging form.

public static string CheckBoxList(this HtmlHelper helper, string name, IEnumerable<SelectListItem> items)
{
   
var output = new StringBuilder
();
    output.Append(
@"<div class=""checkboxList"">"
);

   
foreach (var item in
items)
    {
        output.Append(
@"<input type=""checkbox"" name="""
);
        output.Append(name);
        output.Append(
"\" value=\""
);
        output.Append(item.Value);
        output.Append(
"\""
);

       
if
(item.Selected)
            output.Append(
@" checked=""chekced"""
);

        output.Append(
" />"
);
        output.Append(item.Text);
        output.Append(
"<br />"
);
    }

    output.Append(
"</div>"
);

   
return output.ToString();
}

That’s nice but how I display tags list with selected tags?

Creating tags list

As a next thing we have to create tag list that we can show on event creating and editing forms. Having event tags list and all tags list is not enough for us. We have to create list of SelectListItem objects and give it to our view. Here is my implementation of method that returns me appropriate SelectItemList list that is based on event and tags data.

private IEnumerable<SelectListItem> GetEventTagsSelection(Event evt, IEnumerable<Tag> tags)
{
   
var result = new List<SelectListItem
>();

   
foreach (var tag in
tags)
    {
       
var item = new SelectListItem
        {
            Text = tag.Title,
            Value = tag.Id.ToString(),
            Selected = evt.Tags.Contains(tag)
        };

        result.Add(item);
    }

   
return result;
}

GetEventsTagSelection() method accepts event and all tags list. Based on this information it creates list of all tags and selects the ones that belong to event. Here is the example of checkbox list generated by CheckBoxList() extension method.

ASP.NET MVC checkbox list

So, seems like real. In my next posting about CheckBoxList I will show you how to update tags in controller action that is used to save event data.

Conclusion

Extending ASP.NET MVC views by custom helper methods is easy and straightforward. As we saw it was not complex task to create checkbox list method that outputs fully functional list of check boxes. One annoying thing was that we had to create method that converted tags to SelectListItem objects but it was still nothing complex. In next posting I will show you how to update event tags that were posted back from form with checkbox list.

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    7 thoughts on “ASP.NET MVC: Implementing CheckBoxList

    • May 6, 2011 at 4:01 am
      Permalink

      Few things,

      1) typo in output.Append(@” checked=””chekced”””);

      2) You should be html encoding name and item.Text, and html attribute encoding item.value.

      3) You should also be returning MvcHtmlString instead of string, so that .NET 4.0 and Razor don’t automatically Html encode your extension method’s output.

    • August 11, 2011 at 10:15 pm
      Permalink

      I am trying to implement a ChecboxList with Client Side validation. Can you please post some code about how it can be done.
      Thanks,

    • November 9, 2011 at 7:00 pm
      Permalink

      you should use tags for text, otherwise you will have to click on the small checkbox itself to select it

    • February 22, 2012 at 9:39 am
      Permalink

      Hi,
      I am new to Umbraco5 and MVC3 as well.

      Can you post the complete the source code? Or can you elaborate which method to write in Model, in Controller?
      How to pass the model to the View?

    • July 25, 2012 at 9:15 pm
      Permalink

      @Html.CheckBoxList(“mycheckboxes”, mySelectListItems)

    • Pingback:ASP.NET MVC: Getting selected values from CheckBoxList | Gunnar Peipman - Programming Blog

    Leave a Reply

    Your email address will not be published. Required fields are marked *