Geeks With Blogs
.Nettuce Code Salad

This has been done a few times, here's my attempt:

         public static MvcHtmlString CheckBoxListFor<TModelTValue>(this HtmlHelper<TModel> htmlHelperExpression<Func<TModel, TValue>> expressionwhere TValue : IEnumerable<object>
        {
            var name = expression.Body is ParameterExpression ? ((ParameterExpression)expression.Body).Name : ((MemberExpression)expression.Body).Member.Name;
            var sb = new StringBuilder("<ul class='checkboxlist'>");
            var values = ((IEnumerable<object>)expression.Compile().Invoke(htmlHelper.ViewData.Model)).Select(x => x.ToString());
            foreach (var value in values)
            {
                sb.Append(string.Format("<li>{0} <input type='checkbox' name='{1}' value='{2}' /></li>"valuenamevalue));
            }
            return new MvcHtmlString(sb.Append("</ul>").ToString());
        }

I included a ParameterExpression just in case the model is an IEnumerable<T> so if your view looks like this:

@model IEnumerable<string>
@using (Html.BeginForm())
{
    @Html.CheckBoxListFor(items => items)
    <input type="submit" value="submit" />
}

Your action can do this:

        [HttpPost]
        public ActionResult Index(IEnumerable<stringitems)
        {
            return View("Result"items);
        }

There's more! Needed to adapt this today to allow for a separate name and value:

 

  public static MvcHtmlString CheckBoxListFor<TModel, TItem>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, IEnumerable<TItem>>> listExpression, Func<TItem, object> checkboxName, Func<TItem, object> checkboxValue)
        {
            var listName = listExpression.Body is ParameterExpression ? ((ParameterExpression)listExpression.Body).Name : ((MemberExpression)listExpression.Body).Member.Name;
            var sb = new StringBuilder("<ul class='checkboxlist'>");
            foreach (var value in listExpression.Compile().Invoke(htmlHelper.ViewData.Model))
            {
                sb.Append(string.Format("<li>{0} <input type='checkbox' name='{1}' value='{2}' /></li>", checkboxName.Invoke(value), listName, checkboxValue.Invoke(value)));
            }
            return new MvcHtmlString(sb.Append("</ul>").ToString());
        }
Posted on Friday, May 20, 2011 11:33 PM | Back to top


Comments on this post: MVC CheckBoxListFor Helper Extension

# re: MVC CheckBoxListFor Helper Extension
Requesting Gravatar...
...an example with multiple arguments?
Left by leo on May 08, 2012 1:41 PM

Your comment:
 (will show your gravatar)


Copyright © Jon Canning | Powered by: GeeksWithBlogs.net