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

时间:2016-05-27 06:12:05

标签: c# jquery ajax asp.net-mvc controller

我创建了一项调查。对于整个调查,我只有View和每个问题的局部视图。我也有一个分页。所有这些都在下图中展示。 enter image description here
现在,人们可以使用GetAnswersMulti方法将表单(整个问题)发布到服务器。 (我需要异步发布表单)。我想添加一项功能 - 当人们看到最后一个未回答的问题时 - 按钮从接听更改为接听并退出。我想通过删除一个按钮并使用特定的Url添加另一个按钮来实现。问题是 - 服务器应该检查这个问题是否是最后一个。 我尝试异步调用控制器中的相应方法并获取返回值。 我从SO那里尝试了很多,而且我得到了什么:
查看

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

控制器

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

现在调用控制器中的方法并传递idQuestion。控制器中的方法返回true(当它是最后一个问题时)。然后我在js代码中失败了。 请帮帮我。我通过SO搜索了2天,但没有发现任何对我有用的东西。

4 个答案:

答案 0 :(得分:1)

也许最好使用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);" />
    }

答案 1 :(得分:1)

为了让你的动作返回Json,那么动作的返回类型需要是Json。由于操作返回布尔值(true或false),因此不会将其视为操作方法。它需要返回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});
}

请注意,当我像return Json(new{ d = true});那样返回Json时,会有一个匿名变量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.
     }
    }

答案 2 :(得分:1)

你能这样试试吗?

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

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

答案 3 :(得分:0)

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