0

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. enter image description here
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.

25
  • What are you trying to do? Why are you combining both Ajax.BeginForm() and jquery ajax? You $.ajax calls the Survey method in IsLastQuestionController (you have the parameters the wrong way around) and it does not even pass a value for idQuestion And what is your GetAnswersMulti() method in SurveyController? Commented May 27, 2016 at 6:17
  • @StephenMuecke Sorry, I edited answer and now pass parameter to function. I tried to do all things in controller method (called by submit) and couldn't cope with it too. I asked the question here and people adviced me to follow this method as far as I understood. Commented May 27, 2016 at 6:24
  • Your not passing anything - all you have is data: "{}", And I have never seen that question you linked to let alone give you any advice on it. Its impossible to understand what your trying to do here. (and you edit now calls a isLast2() function which does not even exist) Commented May 27, 2016 at 6:28
  • @StephenMuecke they adviced by sending a link to another question. I need to post form via ajax and at the same time to check if this question is last one. If so - remove the button. Commented May 27, 2016 at 6:31
  • 1
    @VitaliiIsaenko, You have not explained anything in the question. Sorry to be harsh, but almost every line of code in you question has errors and nothing could possibly work. If you do not clearly explain what is is that view is for and what is is that you trying to achieve, no one can give you a correct answer. Commented May 27, 2016 at 7:11

4 Answers 4

1

Maybe better to use Html.Beginform() and use this script:

       <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($.parseJSON(msg.d));
                        if (msg == "True") {
                           $(".submitbutton").remove();
                }
                    },
                    error: function (e) {
                        alert("Fail");
                    }
                });

            }
        </script>

@using (Html.BeginForm("GetAnswersMulti", "Survey", FormMethod.Post)
<input type="text" id="commentText" placeholder="Введите коментарий"/>
        <input value="Ответить" type="submit"
               class="btn btn-default submitbutton"
               onclick="isLast(@Model.FirstOrDefault().IdQuestion);" />
    }
Sign up to request clarification or add additional context in comments.

3 Comments

@Vitalii Isaenko , you didn't pass any values to your action,
@Vitalii Isaenko , also have in mind that asp.net returns boolean values as string "True"
Sorry for confusing you - I use if (msg.d == "True") and only isLast() function. I tried this but got fail again.
1

In order for your action to return Json, then the return type of the action needs to be Json. Since the action returns a boolean value (true or false), then it is not considered as an action method. It needs to return an ActionResult type like so

public ActionResult IsLastQuestion(int idQuestion)
 {
Question question = Manager.GetQuestion(idQuestion);
List<Question> questions = Manager.SelectQuestions(question.idSurvey);
if (questions.Count == Manager.GetCountQuestionsAnswered(
    question.idSurvey,SessionUser.PersonID))
    return Json(new{ d = true});
else
    return Json(new{ d = false});
}

Notice that when I return Json like so return Json(new{ d = true});, there is an anonymous variable d which is the boolean value you will check in your success function like this

success: function (msg){
                    alert($.parseJSON(msg.d));
                    if (msg.d === true) {
                       $(".submitbutton").remove();
            }
                    else if(msg.d == false){
      // Do something if false retured.
     }
    }

3 Comments

I tried - look at updated question please. Unfortunately I get fail.
Have you placed a break point at the action method to see if it gets hit?
Since you are sending to the controller a post ajax call you need to add the [HttpPost] attribute at the top of the action.
1

Can you try like this?

[HttpGet]
public ActionResult IsLastQuestion(int idQuestion)
{
    Question question = Manager.GetQuestion(idQuestion);
    List<Question> questions = Manager.SelectQuestions(question.idSurvey);
    if (questions.Count == Manager.GetCountQuestionsAnswered(question.idSurvey, SessionUser.PersonID))
        return Content("True", "application/json" );
    else
        return Content("False", "application/json" );
}

In your ajax call-

    function isLast(data) {
    $.ajax({
        type: "GET",
        url: "@Url.Action("Survey", "IsLastQuestion")",
        data: { idQuestion: data },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (result)
        {
            //check the value inside result here..
        },
        error: function (e) {
            alert("Fail");
        }
    });
}

7 Comments

Do you mean with bool method type? I tried, didn't help. And with [HttpPost] attribute too.
Looks like some problem with the parameter. Can you check if your isLast() function gets hit by the button click? Can you try removing the data property and the method parameters (just try calling the function without parameters)?
Parameter is passed and the function also calls method in controller with corresponding value of parametr. But, probably it can't take the msg from method in controller or something else.
Again I have alert with Fail.
Since you are just querying your Controller by passing a single parameter value, you can do it by 'GET'. I have edited my answer. Please check if the value from Controller Action method is passed to ajax success.
|
0

Parameter is needed in IsLastQuestion function and you dont pass it in script.

function isLast(parameter) {
    $.ajax({
        type: "POST",
        url: "@Url.Action("Survey", "IsLastQuestion")",
        data: "{parameter}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg){
            alert($.parseJSON(msg.d));
        },
        error: function (e) {
            alert("Fail");
        }
    });
    if (isLast2 == true) {
        $(".submitbutton").remove();
    }
}

1 Comment

You are rigth! Anyway I get fail.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.