-1

So I am making a survey website where you can create survey forms and fill them after, my question is if I have a question where i have a collection of it's options with bool if the option is marked on filling or not, how do I set that value to the model when i click onto Submit form button In short words get all marked answers from the questions, pass them to the controller as a separate view model that contains only the ID of the question and the given answer

Here is the class of the question :

 public class OptionsQuestionVM
    {
        public Guid Id { get; set; }

        public Guid FormId { get; set; }

        public bool IsAnswered { get; set; }
        public bool IsDeleted { get; set; }


        public string Name { get; set; }
        public ICollection<OptionModelVM> Options { get; set; }
        public bool IsRequired { get; set; }
        public bool HasMultipleAnswers { get; set; }

    }

Here is the class of the OptionModelVM:

public class OptionModelVM
    {
        public Guid Id { get; set; }

        public string Text { get; set; }
        public bool IsMarked { get; set; } 
        public OptionsQuestionVM Question { get; set; }
        public Guid OptionsQuestionId { get; set; }
    }

And here is my HTML Code for the checkbox that will be displayed for each question and it's available answers:

@foreach (var item in Model.OptionsQuestions)
                    {
                        if (item.HasMultipleAnswers == true)
                        {
                            <div class="element-checkbox">
                                <hr>
                                <h4>@item.Name</h4>
                                <div class="column column1">


                                    @foreach (var option in item.Options)
                                    {
                                        <label>
                                            <input type="checkbox" name="checkbox[]" value="option 1" />
                                            <span style="font-size:medium">@option.Text</span>
                                        </label>
                                        <br />
                                    }



                                </div><span class="clearfix"></span>
                            </div>
                        }
                        else
                        {

                                <div class="element-checkbox" single>
                                    <hr>
                                    <h4>@item.Name</h4>
                                    <div class="column column1">


                                        @foreach (var option in item.Options)
                                        {
                                            <label>
                                                <input type="checkbox" name="checkbox[]" value="option 1" />
                                                <span style="font-size:medium">@option.Text</span>
                                            </label>
                                            <br />
                                        }



                                    </div><span class="clearfix"></span>
                                </div>

                        }

                    }

And also it would help if someone tells me how to set the HasMultipleAnswers bool into the checkbox, so that when its true you can mark more than 1 answer, when false you can choose only 1 Thank you :)

2 Answers 2

0

Model binding is done through element names. The easiest way to accomplish model binding is to use the html helpers. At the top of your view put:

@model OptionsQuestionVM

then where you want a checkbox use (IsAnswered for example):

@Html.CheckboxFor(m => m.IsAnswered, new { @class="any classes"})

If you have a form surrounding this field, when the form is submitted that field will be passed to the server.

Your controller:

public ActionResult SomeName(OptionsQuestionVM model){}

where model is holding the values from the view.

As for handling multiple answers and binding that to a list. This is called complex model binding take a look at this article: https://krishnrajrana.wordpress.com/2015/12/15/asp-net-mvc-post-a-list-or-collection-of-complex-types-with-non-sequential-indices/ and this question from StackOverflow: MVC post a list of complex objects

1
  • From this information you can work on logic to handle different answers for questions, and binding your model to have answers bound to the question they are for. Jun 1, 2020 at 15:13
0

First, you need to create a class to receive the ID of the question and answers, and store the field content required by the class in the corresponding place of the view.

Here is the receive class QuestionAnswer:

  public class QuestionAnswer
    {
        public Guid QuestionId { get; set; }
        public List<Guid> Answers { get; set; }
    }

Secondly, the name of the checkboxes corresponding to different question options must be different.

And if the options that can only be single-selected, you can display them in the form of radio buttons.

Since you are involved in multiple models and need to return specific options, I think using ajax to pass is the best solution.

The following is a modification based on your code:

@model WebApplication_core_mvc.Models.MyQuestion
@{
    ViewData["Title"] = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml"; 
}
@section Scripts{ 
    <script>
        $(function () {
            $("form").submit(function () {
                event.preventDefault();
                var questionAnswer = [];
                $("input[type=hidden][name=QuestionId]").each(function () {
                    var question = {
                        QuestionId :$(this).val(),
                        Answers: []
                    };
                    $("input[name=" + question.QuestionId + "]").each(function () {
                        if ($(this).is(":checked")) {
                            question.Answers.push($(this).val());
                        }
                    });
                    questionAnswer.push(question);
                });
                $.ajax({
                    url: $("form").attr("action"),
                    method: 'post',
                    data: { "questionAnswer": questionAnswer},
                })
            })
        })
    </script>

}
<h1>Index</h1>
<form asp-action="SubmitAnswers">
    @foreach (var item in Model.OptionsQuestions)
    { 
        <input type="hidden" name="QuestionId" value="@item.Id"  />
        if (item.HasMultipleAnswers == true)
        {
            <div class="element-checkbox">
                <hr>
                <h4>@item.Name</h4>
                <div class="column column1">
                    @foreach (var option in item.Options)
                    {
                        <label>
                            <input type="checkbox" name="@item.Id" value="@option.Id" />
                            <span style="font-size:medium">@option.Text</span>
                        </label>
                        <br /> 
                    }
                </div><span class="clearfix"></span>
            </div>
        }
        else
        {

            <div class="element-checkbox" single>
                <hr>
                <h4>@item.Name</h4>
                <div class="column column1">
                    @foreach (var option in item.Options)
                    { 
                        <label>
                            <input type="radio" name="@item.Id" value="@option.Id" />
                            <span style="font-size:medium">@option.Text</span>
                        </label>
                        <br /> 
                    }
                </div><span class="clearfix"></span>
            </div>

        }
    }
    <input id="Submit1" type="submit" value="submit" />
</form>

Controller:

public IActionResult SubmitAnswers(List<QuestionAnswer> questionAnswer)
{
   //Do what you want...
    return View();
}

Here is my test result:

enter image description here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.