lundi 26 août 2019

Returning a string of selected values from a checkbox collection

I am building a C# MVC view that includes a field with a series of 4 checkboxes. I can populate the list with the values and return individual values just fine, so the basics of the form appear to work. Here is how the options get populated on the view:

    @for (int i = 0; i < Model.QuesOptions.Count; i++)
                        {
                            <div>
                                @Html.HiddenFor(x => x.QuesOptions[i].Name)
                                @Html.CheckBoxFor(x => x.QuesOptions[i].Checked)
                                @Html.LabelFor(x => x.QuesOptions[i].Checked, Model.QuesOptions[i].Name)
                            </div>}

The ultimate goal is to return a single list of values (ideally comma delimited) of the values of each item checked at at the time of posting. So when the user clicks "submit" on the form, it would be great if a single field on the view model (called "UserAnswer") would populate with a comma delimited string. Is this even possible right on the view model?

I had hopes, probably empty ones, that some variation of this would work: @Html.HiddenFor(model=>model.Ques.UserAnswer, new { Value= Model.QuesOptions.Where(x=>x.Checked).Select(x=>x.Name) })

Or would this be a job for some kind of extension method or HTML helper?

Thank you!




Aucun commentaire:

Enregistrer un commentaire