简体   繁体   中英

ASP.NET MVC Save dynamic creation of fields

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 });
...
   }

}

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 });
      }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM