我有一个场景,当用户提交表格时,我们会向用户提出一个多项选择题,然后将表格切换出来并替换为答案的解释。
我有以下观点
<script type="text/javascript">
$(document).ready(function () {
$('#answerForm').submit(function () {
$.ajax({
type: this.method,
url: this.action,
data: $(this).serialize(),
success: function (result) {
$("#question").toggle(1000);
$("#answer").toggle(1000);
}
});
//alert("Submitted");
return false;
});
});
<div id="question">
<span id="question-display">@Model.Question</span>
<div class="answer-section">
@using (Html.BeginForm("Index", "", FormMethod.Post, new { id = "answerForm" }))
{
for (int i = 0; i < Model.Responses.Count; i++)
{
<div class="reponse">@Html.RadioButtonFor(m => m.SelectedIndex, i, new { @class = "response-radio" })@Model.Responses[i]</div>
}
<input id="submit-button" type="submit" value="Answer" />
}
</div>
<div id="testResponse">Form not submitted</div>
</div>
<div id="answer" style="display:none">
@Model.Explanation
</div>
问题在于,虽然我的表单提交没有按预期导致重定向,但js中“success”函数中的代码似乎没有执行。
控制器:
public ActionResult Index()
{
QuizModel model = new QuizModel()
{
Question = "This is the question",
Explanation = "This is the explanation",
UserHasAnswered = false
};
return PartialView(model);
}
//
// POST: /Quiz/Submit
[HttpPost]
public ActionResult Index(QuizModel model)
{
if (ModelState.IsValid)
{
int? selected = model.SelectedIndex;
model.UserHasAnswered = true;
model.Explanation = "Explication";
return Json(new
{
success = true,
});
}
return Json(new
{
success = false,
});
}