Razor CheckBoxFor on List

2019-09-21 01:32发布

问题:

I can't seem to figure out how to get a list of strings to render in my form as checkboxes. Tried a few things from various sites and questions/answers on here with no luck.

MODEL

    var model = new ProjectModel()
    {
        ProjectType = new List<string>()
        {
            "Brand Creation",
            "Web Design",
            "Graphic Design",
            "Custom Programming",
            "E-Commerce",
            "Other"
        },
    };

VIEW - I've tried the following ways.

                @foreach (var item in Model.ProjectType)
                {
                    @Html.CheckBoxFor(model => true, item)
                    <br />
                }

                    @foreach (var item in Model.Budget)
                    {
                        @Html.CheckBox(item)
                        <br />
                    }

回答1:

I would rather use Enum to display checkboxes. I know it's not your answer but you may consider doing this.

You have to do these step >

  1. Enum

    [Flags]
    public enum ProjectType
    {
        [Display(Name = "Brand Creation")]
        BrandCreation = 1,
        [Display(Name = "Web Design")]
        WebDesign = 2
    }
    
  2. Create Html Extension method

     public static IHtmlString CheckboxListForEnum<T>(this HtmlHelper html, string name, T modelItems) where T : struct
        {
            StringBuilder sb = new StringBuilder();
    
            var displayAttributeType = typeof(DisplayAttribute);
    
            foreach (T item in Enum.GetValues(typeof(T)).Cast<T>())
            {
                FieldInfo field = item.GetType().GetField(item.ToString());
    
                DisplayAttribute attrs = (DisplayAttribute)field.
                              GetCustomAttributes(displayAttributeType, false).FirstOrDefault();
    
                TagBuilder builder = new TagBuilder("input");
                long targetValue = Convert.ToInt64(item);
                long flagValue = Convert.ToInt64(modelItems);
    
                if ((targetValue & flagValue) == targetValue)
                    builder.MergeAttribute("checked", "checked");
    
                builder.MergeAttribute("type", "checkbox");
                builder.MergeAttribute("value", attrs.GetName());
                builder.MergeAttribute("name", name);
                builder.InnerHtml = attrs.GetName();
    
                sb.Append(builder.ToString(TagRenderMode.Normal));
            }
    
            return new HtmlString(sb.ToString());
        }
    
  3. Finally in your View

    @Html.CheckboxListForEnum("ProjectType", @Model.ProjectType)
    
  4. Get posted value

    public ActionResult Index(FormCollection form)
    {
       string[] AllStrings = form["ProjectType"].Split(',');
    
      foreach (string item in AllStrings)
      {
         int value = int.Parse(item);
      }
    }