Gunnar Peipman's ASP.NET blog

ASP.NET, C#, SharePoint, SQL Server and general software development topics.

Sponsors

News

 
 
 
DZone MVB

Links

Social

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

My model: events and tagsMy 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: Output of CheckBoxList

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.

Comments

James Harris said:

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.

# May 6, 2011 12:01 AM

Mayur Madawar said:

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

Thanks,

# August 11, 2011 6:15 PM

Ivan said:

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

# November 9, 2011 2:00 PM

Vishal said:

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?

# February 22, 2012 4:39 AM

DigiMortal said:

Vishal, here is the link to follow-up posting: weblogs.asp.net/.../asp-net-mvc-getting-selected-values-from-checkboxlist.aspx

You can find there how to get values of selected checkboxes in your controller when user wants to save data.

# February 25, 2012 5:42 AM

MuhammadRizwan said:

How i can call it in view??

# July 25, 2012 3:29 AM

DigiMortal said:

@Html.CheckBoxList("mycheckboxes", mySelectListItems)

# July 25, 2012 5:15 PM