如何传递模型以在mvc4中基于ajax的请求中查看

时间:2014-07-07 23:35:36

标签: ajax asp.net-mvc asp.net-mvc-4

我正在MVC中创建一个基于ajax的测验。以下是问题视图。提交表单时,我将用户选择保存在控制器中,然后需要将下一个问题发送到视图而不重新加载页面。是否可以在ajax请求中从控制器发送/更新模型

@model  DataAccess.Question
@{
ViewBag.Title = "Survey";
Layout = "~/Views/Shared/_Layout.cshtml";
}
  @using (Ajax.BeginForm("Survey", "Tools", new AjaxOptions { UpdateTargetId = "QuestionContent", HttpMethod = "Post", InsertionMode = InsertionMode.Replace }, new { QuestionId = Model.QuestionId }))
    {
        <div id="QuestionContent">
            <h2>Welcome To Quiz</h2>

            <fieldset>
                <p>
                    Question
                    @Model.QuestionId of @ViewBag.QuestionCount:
                </p>
                <p>
                    @Model.Description.
                </p>
                <ul style="list-style:none;">
                    @foreach (var item in Model.Answers)
                    {
                        <li> @Html.RadioButton("ChoiceList", item.score) @item.AnswerDesc</li>

                    }
                </ul>

                <input type="submit" value="Next" id="submitButton" />
            </fieldset>

        </div>
    }

1 个答案:

答案 0 :(得分:1)

使用jQuery实现AJAX POST并返回包含所有下一个Q&amp; A信息的JSON对象要容易得多。使用js / jQuery设置<div>或任何其他html元素。发布和重新加载是一种痛苦,并成为一种过时的方法。

例如,您可以拥有此ViewModel类:

public class Answer
{
    public int QuestionId {get; set;}
    public string Answer {get; set;}
}

构建一个包含div&amp;的视图Q&amp;输入控制甲

通过AJAX实施应答按钮POST:

 $.ajax({
    type: "POST",
    url: "/Exam/HandleAnswer" ,
   data: { QuestionId:  _questionId, Answer: $("#txt_answer").val() },
  success: function (resp) {
    if (resp.Success) {
       $("#div_Question").text( resp.NextQuestionMessage);
       _questionId = resp.NextQuestionId,
       $("#txt_answer").val(''");  //clear
    }
    else {
      alert(resp.Message);
    }
   }
 });

在ExamController中:

[HttpPost]
public ActionResult HandleAnswer(Answer qa)
{
     //use qa.QuestionId to load the question from DB...

     //compare the qa.Answer to what the DB says...

    //if good answer get next Question and send as JSON or send failure message..

   if (goodAnswer)
   {
      return Json(new { Success = true, NextQuestionMessage = "What is the capital of of Texas", NextQuestionId = 123});
   }
   else{
      return Json(new { Success = false, Message = "Invalid response.."});
   }

}