如何通过Ajax从视图中调用控制器中的方法? [英] How to call method in controller from view via ajax?

查看:65
本文介绍了如何通过Ajax从视图中调用控制器中的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建一个调查.对于整个调查,我只有视图",对于每个问题,我只有部分"视图.我也有分页.所有这些都在下面的图片中进行了展示.
现在,人们可以使用 GetAnswersMulti 方法将表单(整个问题)发布到服务器.(我需要异步发布表单).我想添加一个功能-当用户看到最后一个未回答的问题时-按钮从答案更改为答案并退出.我想通过删除一个按钮并添加另一个具有特定网址的按钮来实现.问题是-服务器应检查该问题是否最后一次.我尝试异步调用控制器中的相应方法并获取返回值.我从SO上做了很多尝试,然后得出了以下结论:
查看

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

控制器

[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天,但没有找到对我有用的东西.

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.

推荐答案

您可以尝试这样吗?

[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通话中-

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

这篇关于如何通过Ajax从视图中调用控制器中的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆