2014-01-25 2 views
3

Я узнаю asp.net mvc, и я не могу решить проблему В моем представлении есть функция JS для динамического создания Вопрос Ввод, проблема в том, что я не знаю, как сохраните созданные вопросы на сервере. Теперь мой контроллер получает два QuestionText, но пользователь может создать неограниченное количество вопросов, как я могу сохранить их, не увеличивая количество параметров.ASP.NET MVC Сохранить динамическое создание полей

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

} 

ответ

2

Вы можете использовать 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 }); 
     } 
} 
+0

это работает, спасибо! –

Смежные вопросы