【问题标题】:ASP.NET MVC Save dynamic creation of fieldsASP.NET MVC 保存动态创建字段
【发布时间】:2014-01-25 09:25:28
【问题描述】:

我学习了asp.net mvc,但无法解决问题 在我的视图中有动态创建问题输入的JS功能,问题是我不知道如何将生成的问题保存在服务器上。现在,我的控制器收到两个 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 });
...
   }

}

【问题讨论】:

    标签: c# javascript asp.net-mvc


    【解决方案1】:

    您可以使用 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 });
          }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-18
      • 1970-01-01
      • 2013-07-07
      • 1970-01-01
      • 2023-03-28
      • 2010-12-02
      相关资源
      最近更新 更多