I create a survey. For whole survey I have only View and for every question partial view. Also I have a pagination. All these demonstrated in the picture below.
Now people can post the form (whole question) to server using GetAnswersMulti
method. (I need the form be posted asynchronously). I want to add a feature - when person see the last not answered question - button changes from Answer to Answer and exit. I suppose to do it by removing one button and add another with specific Url. The problem is - server should check if this question is last.
I try to call corresponding method in controller asynchronously and get the returned value.
I tried much from SO and there is what I came to:
View
<script>
function isLast(data) {
$.ajax({
type: "POST",
url: "@Url.Action("Survey", "IsLastQuestion")",
data: { idQuestion: data },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("success");
if (msg == "True") {
$(".submitbutton").remove();
}
},
error: function (e) {
alert("Fail");
}
});
}
</script>
@using (Html.BeginForm("GetAnswersMulti", "Survey", FormMethod.Post))
{
<input value="Ответить" type="submit"
class="btn btn-default submitbutton"
onclick="isLast(@Model.FirstOrDefault().IdQuestion);" />
}
Controller
[HttpPost]
public ActionResult IsLastQuestion(int idQuestion)
{
Question question = Manager.GetQuestion(idQuestion);
List<Question> questions = Manager.SelectQuestions(question.idAnketa);
if (questions.Count == Manager.GetCountQuestionsAnswered(question.idAnketa, SessionUser.PersonID))
return new JsonResult() { Data = true };
else
return new JsonResult() { Data = false };
}
[HttpPost]
public void GetAnswersMulti(List<PossibleAnswerVM> possibleAnswers)
{
List<Answer> answers = new List<Answer>();
foreach (PossibleAnswerVM possibleAnswer in possibleAnswers)
{
Answer answer = new Answer();
answer.datetimeAnswer = DateTime.Now;
answer.idOption = possibleAnswer.IdOption;
answer.idPerson = SessionUser.PersonID;
if (possibleAnswer.IsChecked)
{
if (IsValid(answer))
answers.Add(answer);
}
}
Manager.SaveAnswers(answers,possibleAnswers.FirstOrDefault().IdQuestion, SessionUser.PersonID);
}
Now method in controller is called and idQuestion is passed. Method in controller returns true (when it IS the last question). Then I get fail in js code. Help me with this please. I searched 2 days through SO but didn't find anything that works for me.