3

I learn asp.net mvc and i can not solve the problem In my View have JS function for dynamic creation Question input, the problem is that I do not know how to save the generated questions on the server. Now, my controller receives two QuestionText, but the user can create an unlimited number of questions, how can I save them without increasing the number of parameters.

    @using (Html.BeginForm())
    {
    ...  
         <div id="Questions">
         </div>
         <a href="javascript:" class="m-btn" onclick="AddQuestion();">Add Question</a>
    ...
    }
        <script type="text/javascript">
            countQ = 1;
            function AddQuestion() {
                var id = 'questionText' + countQ;
                $('<p>').appendTo('#Questions');
                $('<a href="javascript:" onclick="$(\'#' + id + '\').append(\'[code]...[/code]\');" class="m-btn">Код</a>').appendTo('#Questions');
                $('<textarea/>').attr({ class: 'QuestionText', type: 'text', name: 'questionText' + countQ, id: 'questionText' + countQ, placeholder: 'Question №' + countQ }).appendTo('#Questions');
                countQ = countQ + 1;
            }
        </script>

[Httppost]
public ActionResult Add(Interview interview, string questionText1, string questionText2)
  {
           interview.Questions = new List<Question>();
           interview.Questions.Add(new Question() { Text = questionText1, InterviewID = interview.InterviewID });
           interview.Questions.Add(new Question() { Text = questionText2, InterviewID = interview.InterviewID });
...
   }

}

1 Answer 1

2

You can use FormCollection for search and save user question

[Httppost]
public ActionResult Add(Interview interview, FormCollection formCollection)
  {
string[] questions = formCollection.AllKeys.Where(c => c.StartsWith("questionText")).ToArray(); //search question input
  if (questions.Length > 0)
    {
     interview.Questions = new List<Question>();
     foreach (var question in questions)
      {
       if (!string.IsNullOrWhiteSpace(formCollection[question]))
      interview.Questions.Add(new Question() { Text = formCollection[question], InterviewID = interview.InterviewID });
      }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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