July 9, 2012

CheckBox lists in ASP.NET MVC

I’m in the process of pulling a lot of the code from personal projects into Fabrik.Common, a project full of useful stuff that I’ve released as open source.

Today I was moving some of my HTML Helpers across and came across a nice one I wrote for generating Checkbox lists.

Since there is no built in solution for this in ASP.NET MVC a common suggestion is to loop through the list in your view and render a checkbox:

@foreach (var item in Model.SubscriptionSources) {
	<input type="checked" name="SelectedSources" value="@item">@item
}

You the input name should correspond to an IEnumerable property on your model e.g:

[DisplayName("How did you hear about us?")]
public IEnumerable<string> SelectedSources { get; set; }

The ASP.NET MVC modelbinder is smart enough to map the selected items to this property.

Although the above approach works just fine, it becomes a bit trickier when you need to render multiple pre-selected items.

Attempting to do this inside your View is going to result in a lot of spaghetti, so naturally I created a Html Helper to handle this.

Rather than duplicating the source on my blog, you can view it on GitHub.

Using the helpers is easy. Below is the model we are passing to our view. We’ll initialize the available and selected options inside the constructor but these could easily come from a database etc.

public class SubscribeModel {
	
	// This property contains the available options
	public SelectList SubscriptionSources { get; set; }

	// This property contains the selected options
	public IEnumerable<string> SelectedSources { get; set; }

	public SubscribeModel() {
		SubscriptionSources = new SelectList(
			new[] { "Google", "TV", "Radio", "A friend", "Crazy bloke down the pub" });

		SelectedSources = new[] { "Google" };
	}
}

When we generate our form we can use the strongly typed version of the helper, CheckBoxListFor:

<div class="editor-label">
    @Html.LabelFor(model => model.SelectedSources)
</div>
<div class="editor-field">
    @Html.CheckBoxListFor(model => model.SelectedSources, Model.SubscriptionSources)
    @Html.ValidationMessageFor(model => model.SelectedSources)
</div>

And the result:

CheckBoxList

Simple.

© 2022 Ben Foster