mercredi 11 mai 2016

Select Multiple Checkboxes on MVC form

I have a model called AnswerSheet, it is a bunch of String Answers. Snip below:

public class PassengerAnswerSheet
    {
        public int ID { get; set; }

        [Required]
        [Display(Name = "Question 1")]
        public string Q1 { get; set; }

        [Required]
        [Display(Name = "Question 2")]
        public string Q2 { get; set; }

For each answer, I have multiple checkboxes, I want the answer to be a string generated by the selected checkboxes text.

The checkboxes are built using a different model, an animal for this example:

public class Animal
    {
        public bool IsChecked { get; set; }
        public String Name { get; set; }
    }

Currently I can get the Question to display what I want (sort of) using this code on my Razor Form:

<div class="form-group">
            @Html.LabelFor(model => model.Q1, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @foreach(var  animal in Curbside.Helpers.AnswerLists.CreateAnimalsList())
                {
                    string Hi = (animal.Name);  
                    @Html.CheckBoxFor(item => animal.IsChecked)
                    @Hi 
                    <br />
                }
                @Html.EditorFor(model => model.Q1)                
                @Html.ValidationMessageFor(model => model.Q1)
            </div>
        </div>

Now what I need to figure out, is how to have the checked boxes for the "Foreach" section generate a string when the user submits a form, example it will generate "Cow, Pig" as the answer for Q1 if the user has checked the boxes beside Cow and Pig. I've been reading a lot on this but haven't figured it out, and I feel stuck here. Will continue to investigate. Obviously I need ot get rid of @Html.EditorFor but I don't know what to replace it with or how to use it.

Aucun commentaire:

Enregistrer un commentaire