ASP.NET MVC Checkbox Group

后端 未结 5 800
渐次进展
渐次进展 2020-12-29 10:36

I am trying to formulate a work-around for the lack of a \"checkbox group\" in ASP.NET MVC. The typical way to implement this is to have check boxes of the same name, each

5条回答
  •  爱一瞬间的悲伤
    2020-12-29 10:55

    Behold the final solution:

    public static class Helpers
    {
        public static string CheckboxGroup(this HtmlHelper htmlHelper, Expression> propertySelector, int value) where TProperty: IEnumerable
        {
            var groupName = GetPropertyName(propertySelector);
            var modelValues = propertySelector.Compile().Invoke(htmlHelper.ViewData.Model);
    
            var svalue = value.ToString();
            var builder = new TagBuilder("input");
            builder.GenerateId(groupName);
            builder.Attributes.Add("type", "checkbox");
            builder.Attributes.Add("name", groupName);
            builder.Attributes.Add("value", svalue);
            var contextValues = HttpContext.Current.Request.Form.GetValues(groupName);
            if ((contextValues != null && contextValues.Contains(svalue)) || (modelValues != null && modelValues.Contains(value)))
            {
                builder.Attributes.Add("checked", null);
            }
            return builder.ToString(TagRenderMode.Normal);
        }
    
        private static string GetPropertyName(Expression> propertySelector)
        {
            var body = propertySelector.Body.ToString();
            var firstIndex = body.IndexOf('.') + 1;
            return body.Substring(firstIndex);
        }
    }
    

    And in your view:

                            <%= Html.CheckboxGroup(model => model.DocumentCoverCustom, "1")%>(iv),
    <%= Html.CheckboxGroup(model => model.DocumentCoverCustom, "2")%>(vi),
    <%= Html.CheckboxGroup(model => model.DocumentCoverCustom, "3")%>(vii),
    <%= Html.CheckboxGroup(model => model.DocumentCoverCustom, "4")%>(ix)

提交回复
热议问题