0

我有一个问题列表,我想通过 ajax 调用保存用户答案。例如,我有 50 个问题,不确定是否需要遍历所有 50 个问题并将每个答案发送到控制器(保存),或者是否可以将结果作为大数据发送到控制器。

我的观点:

@using COPSGMIS;
@model IEnumerable<COPSGMIS.Models.Quiz>

@{
    ViewBag.Title = "Questionaire";
}
<h2>Questionaire</h2>
  <input type="hidden" id="currentstep" name="currentstep" />
   @using (Html.BeginForm("Questionaire", "Question", FormMethod.Post, new { id = "SignupForm" }))
   {
       <div id="wizardtemplate">       
            @foreach (var step in Model)       
            {
              <fieldset class="wizard">
                <div class="page_Title"> @Html.DisplayFor(modelItem => step.Title)</div>               
                @foreach (var question in step.Results)
                {
                ... code removed ....
                <label for="question">@Html.DisplayFor(modelItem => question.NumberedQuestion)</label>  
                 @Html.Raw(Html.DisplayControl(question.QuestionID, question.Choices, question.AnswerValue,question.ControlType)) 
                 </div>                               
                 @Html.Partial("_Comment", question)
               <hr />
                }
              </fieldset>
            }       

呈现的 HTML:

<label for="question">3. This is a sample question (2) for the questionare?</label>  
                 <div class='answer'><input type='date' id='3' name='3' value='2012-12-10' /></div> 
                 </div>                               
 ... code removed ....

 <label for="question">4. This is a sample question (3) for the questionare?</label>  
                 <div class='answer'><input type='text' id='4' name='4' value='999' /></div> 
                 </div>         

模型:

 public class Quiz
    {
        public int ReviewID { get; set; }
        public int StepID { get; set; }
        public string Title { get; set; }
        public virtual IEnumerable<Result> Results { get; set; }
    }

阿贾克斯调用:

function SaveAnswer(//not sure what needs to be passed) {

    $.ajax({
        url: '/Question/SaveQuestionaire',
        type: 'POST',
        cache: false,
        dataType: 'json',
        data: ({
            // not sure what this will look like?
        }),
        error: function (jqXHR, textStatus, errorThrown) {
            alert(errorThrown);
        },
        success: function (json) {
            // Message to confirm save
        }
    });
}
4

1 回答 1

0

为了便于使用,很容易为每个问题发送一个 AJAX 请求。但是,您应该能够将一组条目推送到服务器,并将其解释为一组对象。

您可以像这样构建一个数组:

var array = [];

for (var i = 0; ...)
   array.push(items[i]);

然后将阵列推送到服务器。

由于您正在构建一个大型表单,您还可以尝试执行以下操作:

 $.ajax({
        url: '/Question/SaveQuestionaire',
        type: 'POST',
        cache: false,
        dataType: 'json',
        data: $("#SignupForm").serialize(), // creates an object for you

但要让它工作,你必须小心它生成的 ID,因为它用于重新创建对象数组。不确定您采用的方法是否适合这一点。

于 2013-01-03T17:42:53.360 回答