Sunday, 14 August 2011

CheckboxListFor in MVC3 with Unobtrusive Validation


Download source code : https://github.com/Azadehkhojandi/CheckboxListFor
Related Posts





I've had time to look at my 'Checkboxlistfor' method and I've found out that  validation tags (data- ) are missed with using 'Checkbox' HTML tag.
I find GetUnobtrusiveValidationAttributes method to retrieve validation data tags.I add an extra optional parameter to add css class name for UL tag.
I believe there should be a way to pass a wrapper for check boxes or even better pass desire template.
like something which is mentioned here
 


public static MvcHtmlString CheckBoxListFor<TModel, TEnum>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, IEnumerable<TEnum>>> expression, string ulClass = null)
        {
            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
            var unobtrusiveValidationAttributes = htmlHelper.GetUnobtrusiveValidationAttributes(metadata.PropertyName, metadata);

            var html = new TagBuilder("ul");
            if (!String.IsNullOrEmpty(ulClass))
                html.MergeAttribute("class", ulClass);

            string innerhtml = "";
            var model = metadata.Model as IEnumerable<TEnum>;
            foreach (var item in Enum.GetValues(typeof(TEnum)))
            {

                bool ischecked = (model == null) ? false : model.Any(x => x.ToString() == item.ToString());

                var liBuilder = new TagBuilder("li");

                var inputBuilder = new TagBuilder("input");
                inputBuilder.MergeAttribute("type", "checkbox");
                inputBuilder.MergeAttribute("name", metadata.PropertyName, true);
                inputBuilder.MergeAttribute("id", item.ToString(), true);
                inputBuilder.MergeAttribute("value", item.ToString(), true);
                inputBuilder.MergeAttributes(unobtrusiveValidationAttributes);
                if (ischecked)
                {
                    inputBuilder.MergeAttribute("checked", "'checked'");
                }

                liBuilder.InnerHtml = inputBuilder.ToString() + htmlHelper.Label(metadata.PropertyName + "." + item, Enum.GetName(typeof(TEnum), item).ToString());
                innerhtml = innerhtml + liBuilder;

            }
            html.InnerHtml = innerhtml;
            return new MvcHtmlString(html.ToString());


        }

Post a Comment