0

I am developing a survey application using Asp.Net Mvc. I'm at the end of the project, but I have a problem. The customer who has the survey link enters the link and sees the interview. The questions in the questionnaire and their options are created dynamically. The other option feature of some questions can fill one text fields for each question. The customer who will vote for the questionnaire has to vote all the questions with the radio button. As I said, in some questions 'Other' option activates a text field and enters text here. The customer submitting the vote submits the survey. When submitting, all questions must be answered. How can I do this using javascript unobstrusive. Do I have to define a rule? I am not familiar with Javascript unobstrusive. I'm waiting for your help by throwing pieces of sample code.

Form

 @using (Html.BeginForm("SubmitSurvey", "Survey", FormMethod.Post, new { onsubmit = "return SubmitForm(this)" }))
    {
        @Html.AntiForgeryToken()
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        @Html.HiddenFor(model => model.Token)           
        <div class="card">
            <div class="card-header bg-gradient-blue "><span class="badge badge-warning"><i class="fa fa-server"></i></span><b> @Model.SurveyName</b></div>
            <div class="card-body" style="overflow-y: auto; max-height: 100%" id="questionList">
                @{ int i = 0; }
                @foreach (SurveyQuestions surveyQuestion in Model.SurveyQuestions)
                {
                    <div class="card" style="margin-bottom: 5px">
                        <div class="card-header bg-gradient-blue"><span class="badge badge-warning">Question @(++i).</span> @surveyQuestion.Questions.QuestionName</div>
                        <div class="card-body" id="questionPortlet">
                            @foreach (Options option in surveyQuestion.Questions.Options)
                            {
                                <div class="custom-control custom-radio">
                                    @Html.RadioButton("optionRadioButton-" + option.QuestionId, "option_" + option.QuestionId + "_" + option.OptionId, new { id = "option_" + option.QuestionId + "_" + option.OptionId, @class = "custom-control-input" })
                                    @Html.Label("option_" + option.QuestionId + "_" + option.OptionId, option.OptionName, new { @class = "custom-control-label font-weight-lighter" })
                                </div>
                            }
                            @if (surveyQuestion.Questions.IsOtherOptionRequired)
                            {
                                <div class="form-group" id="optionOtherParent">
                                    <div class="custom-control custom-radio">
                                        @Html.RadioButton("optionRadioButton-" + surveyQuestion.QuestionId, "optionOther_" + surveyQuestion.QuestionId, new { id = "optionOther_" + surveyQuestion.QuestionId, @class = "custom-control-input" })
                                        @Html.Label("optionOther_" + surveyQuestion.QuestionId, "Other", new { @class = "custom-control-label font-weight-lighter" })
                                    </div>
                                    @Html.TextArea("optionOtherText-" + @surveyQuestion.Questions.QuestionId, "", new { @class = "form-control", rows = "3", id = "optionOtherText_" + surveyQuestion.QuestionId, disabled = "disabled" })
                                </div>
                            }

                        </div>
                    </div>
                }
            </div>

            <div class="card-footer bg-primary d-flex justify-content-end">
                <button type="submit" class="btn btn-warning" style="margin-bottom: 3px; margin-left: 5px; color: black"><i class="fa fa-save"></i>Send Survey</button>
            </div>
        </div>
                    }

Generated html code above

  <div class="card" style="margin-bottom: 5px">
                        <div class="card-header bg-gradient-blue"><span class="badge badge-warning">Question 2.</span> Merinosun hangi modellerini begeniyorsunuz?</div>
                        <div class="card-body" id="questionPortlet">
                                <div class="custom-control custom-radio">
                                    <input class="custom-control-input" id="option_4_2017" name="optionRadioButton-4" type="radio" value="option_4_2017" />
                                    <label class="custom-control-label font-weight-lighter" for="option_4_2017">Model 1</label>


                                </div>
                                <div class="custom-control custom-radio">
                                    <input class="custom-control-input" id="option_4_2018" name="optionRadioButton-4" type="radio" value="option_4_2018" />
                                    <label class="custom-control-label font-weight-lighter" for="option_4_2018">Model 2</label>


                                </div>
                                <div class="custom-control custom-radio">
                                    <input class="custom-control-input" id="option_4_2019" name="optionRadioButton-4" type="radio" value="option_4_2019" />
                                    <label class="custom-control-label font-weight-lighter" for="option_4_2019">Model 3</label>


                                </div>
                                <div class="custom-control custom-radio">
                                    <input class="custom-control-input" id="option_4_2020" name="optionRadioButton-4" type="radio" value="option_4_2020" />
                                    <label class="custom-control-label font-weight-lighter" for="option_4_2020">Model 4</label>


                                </div>
                                <div class="custom-control custom-radio">
                                    <input class="custom-control-input" id="option_4_2021" name="optionRadioButton-4" type="radio" value="option_4_2021" />
                                    <label class="custom-control-label font-weight-lighter" for="option_4_2021">Model 5</label>


                                </div>
                                <div class="custom-control custom-radio">
                                    <input class="custom-control-input" id="option_4_2022" name="optionRadioButton-4" type="radio" value="option_4_2022" />
                                    <label class="custom-control-label font-weight-lighter" for="option_4_2022">Model 6</label>


                                </div>

                        </div>
                    </div>

Editted

How can I convert follows to unobtrusive validation

$(document).ready(function(){
$('#radioValidate').click(function(){
    var check = true;
    $("input:radio").each(function(){
        var name = $(this).attr("name");
        if($("input:radio[name="+name+"]:checked").length == 0){
            check = false;
        }
    });

    if(check){
        alert('One radio in each group is checked.');
    }else{
        alert('Please select one option in each question.');
    }
});
});

enter code here
Sparky
  • 98,165
  • 25
  • 199
  • 285
  • doesn't unobtrusive need data attributes to work? None of your inputs seem to have any – Pete Jan 16 '20 at 13:15
  • Also in your razor, why are you not using `html.labelfor`, `html.textboxfor`, `html.validationfor`, etc. , That way it will add the data attributes for you (if you have annotated your model) – Pete Jan 16 '20 at 13:21
  • Have a look at the form and model in this question: https://stackoverflow.com/questions/33107674/how-to-setup-mvc-5-unobtrusive-validation-correctly-when-appending-the-form-from or this tutorial: https://www.ecanarys.com/Blogs/ArticleID/260/Creating-a-Simple-Form-with-Validation-Using-ASP-NET-MVC-4-Empty-Template – Pete Jan 16 '20 at 13:30
  • The questions and options on the screen come in a list. Should I add data attributes manually in the for loop? I edited the question using html helper. Can you help now –  Jan 16 '20 at 14:46
  • I would do - these are the attributes you need to use: https://stackoverflow.com/questions/11124880/jquery-unobtrusive-validation-attributes-reference/15977785 – Pete Jan 16 '20 at 14:48
  • @Pete I don't get these properties from the object definition, so I have to add them manually. Am I right? –  Jan 16 '20 at 14:50
  • And If there was a simple update form, we would specify the required property of the field with the 'Required' tag in the object definition. But the situation here is different. Is it true? I'm also creating a radio button in 2 different places in the for loop. Should all radio buttons have data_val? –  Jan 16 '20 at 14:51
  • Yes if you don't have a model and want unobtrusive validation, then you would need to add the corresponding data attributes for the validation and error message to the input you want validating – Pete Jan 16 '20 at 14:57
  • I have model Question and Option but return object is different –  Jan 16 '20 at 15:02
  • I have edditted question how to convert it to unobtrusive val –  Jan 16 '20 at 15:54

1 Answers1

0

You can try to manually add rules to your buttons.

   $yourButtonSelector.rules('add', 'required');
   $yourFormSelector.validate();

   if (!$yourFormSelector.valid()) {
         return;
   }

Don't forget to import jQuery validation scripts!

Vinicius Bassi
  • 401
  • 4
  • 14
  • Do I need to manually define the data attributes in the for loop, for example data_val etc .. Because the questions and options are displayed in a list. Dynamically returning to the survey form. –  Jan 16 '20 at 14:48
  • @MehmetŞükrüMUMBUÇOĞLU It should work if you do something like: `$("input:radio").each(function(){ $inputSelector.rules('add', 'required'); });` and then validate() and check if form is valid – Vinicius Bassi Jan 16 '20 at 16:50
  • I am sorry but I dont understand what $inputSelector is? –  Jan 16 '20 at 17:10
  • @MehmetŞükrüMUMBUÇOĞLU It's the selector of the input that you want to add the rule. Idk what are you using for it or if you have one. But it represents the selector of your input element. Could be something like `$(".custom-control-input")` – Vinicius Bassi Jan 16 '20 at 18:15
  • Or you can create an identifier for each that you want to add the rule – Vinicius Bassi Jan 16 '20 at 18:15
  • In fact, I want to make the non-valid card around red. –  Jan 16 '20 at 18:17