简体   繁体   English

ASP.NET MVC保存动态创建字段

[英]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. 我学习asp.net mvc并且我无法解决问题在我的View中有JS函数进行动态创建问题输入,问题是我不知道如何在服务器上保存生成的问题。 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. 现在,我的控制器收到两个QuestionText,但是用户可以创建无限数量的问题,如何在不增加参数数量的情况下保存它们。

    @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 您可以使用FormCollection进行搜索并保存用户问题

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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