dimanche 4 septembre 2016

MVC grouping checkbox fields in form from a list

I have data in model from which checkboxes are created. Functionality wise, it's similar to a survey.

I have free text, drop down and radio button working fine, but checkboxes are a big problem. I want the question answered, thus the field has to be required and checkboxes are "grouped" only if the name is the same, however given the fact that I'm using razor to format the checkboxes, regardless of using CheckBoxFor() method or manually writing <input asp-for="... checkboxes are still not group because ASP Generates the name field which in the ends turns out to be Questions[0].Options[0,1,2,3,...].IsChecked

Without the required attribute everything works fine, but that way people can leave questions unanswered.

@for (var j = 0; j < Model.Questions[i].Options.Count(); j++)
{
    <div class="form-group">
        <div class="form-control">
            @Html.HiddenFor(chk => chk.Questions[i].Options[j].OptionId)

            //CheckboxForMethod
            @Html.CheckBoxFor(chk => chk.Questions[i].Options[j].Checked, new { @required = "required" })

            //Manual method - Name field gets overwritten
            <input asp-for="@Model.Questions[i].Options[j].Checked" name="@Model.Questions[i].Title" required="required" type="checkbox">

            @Html.DisplayFor(chk => chk.Questions[i].Options[j].Title)
          </div>
    </div>
}

Obviously in this kind of situation I can't use a generic property of the question model because 1 bool property can't monitor N options, but going deeper leaves the issue of the html's name attribute..




Aucun commentaire:

Enregistrer un commentaire