Skip to content

Instantly share code, notes, and snippets.

@RichardSlater
Created October 2, 2012 10:49
Show Gist options
  • Save RichardSlater/3818138 to your computer and use it in GitHub Desktop.
Save RichardSlater/3818138 to your computer and use it in GitHub Desktop.
MVC3 Bulk Edit Checkbox HtmlHelper
public static class BulkEditCheckBoxExtensions
{
public static MvcHtmlString BulkEditCheckBoxFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression)
where TModel : IBulkEditViewModel
{
var metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var model = htmlHelper.ViewData.Model as IBulkEditViewModel;
var modelPropertyName = metadata.PropertyName;
var tagBuilder = new TagBuilder("input");
tagBuilder.Attributes.Add("type", "checkbox");
tagBuilder.Attributes.Add("name", "FieldsToUpdate");
tagBuilder.Attributes.Add("value", modelPropertyName);
if (model.FieldsToUpdate != null && model.FieldsToUpdate.Contains(modelPropertyName))
{
tagBuilder.Attributes.Add("checked", "checked");
}
return MvcHtmlString.Create(tagBuilder.ToString());
}
}
public interface IBulkEditViewModel
{
List<string> FieldsToUpdate { get; set; }
}
@RichardSlater
Copy link
Author

This was for a mechanism to add a "Bulk Edit" checkbox to each field in an MVC View, returns a list of fields that have the checkbox checked.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment