简体   繁体   English

如何通过Ajax从视图中调用控制器中的方法?

[英]How to call method in controller from view via ajax?

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. 现在,人们可以使用GetAnswersMulti方法将表单(整个问题)发布到服务器。 (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: 我从SO上尝试了很多,然后得出了以下结论:
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. 现在,将调用控制器中的方法并传递idQuestion。 Method in controller returns true (when it IS the last question). 控制器中的方法返回true(当它是最后一个问题时)。 Then I get fail in js code. 然后我在js代码中失败了。 Help me with this please. 请帮助我。 I searched 2 days through SO but didn't find anything that works for me. 我通过SO搜索了2天,但没有找到对我有用的东西。

Maybe better to use Html.Beginform() and use this script: 最好使用Html.Beginform()并使用以下脚本:

       <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);" />
    }

In order for your action to return Json, then the return type of the action needs to be Json. 为了使您的操作返回Json,操作的返回类型需要为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 它需要像这样返回一个ActionResult类型

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}); 请注意,当我像这样return Json(new{ d = true});时, 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 ,有一个匿名变量d ,它是您将要在success函数中像这样检查的布尔值

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

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- 在您的ajax电话中,

    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");
        }
    });
}

Parameter is needed in IsLastQuestion function and you dont pass it in script. IsLastQuestion函数中需要参数,而您不会在脚本中传递参数。

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();
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM