我学习asp.net mvc并且我无法解决问题 在我的View中有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 });
...
}
}
答案 0 :(得分: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 });
}
}