首页 > 解决方案 > 在 Javascript 中调用控制器的 ActionResult

问题描述

我正在尝试在 javascript 中调用 Controller 内的 ActionResult。

我的AdminController.

[HttpPost]
public ActionResult Logout()
{
    return RedirectToAction("Login", "Login");
}

这是我Logout button在 AdminView 中的。

<a class="navbar-link" id="logout" name="logout" href="#">
    ログアウト
</a>

并尝试在 JAVSCRIPT 中创建一个事件。

  $("#logout").click(function () {
        swal({
            title: "ログアウト?",
            text: "アカウントからサインアウトしますか?",
            icon: "warning",
            buttons: true,
            dangerMode: true,
        })
            .then((willLogout) => {
                if (willLogout) {
                    //swal("Poof! Your imaginary file has been deleted!", {
                    //    icon: "success",
                    //});
                    $.ajax({
                        url: "/Admin/Logout",
                        type: 'POST',
                        success: function (result) {
                            document.location.reload(true);
                        }, 
                        error: function (result) {

                        }
                    });
                }
            });
    });

这样做的主要目的是使用控制器将用户重定向到登录页面。

我尝试设置swal("Poof")...内部.then(willLogout)并且它有效。

但是当我使用 ajax 调用 ActionResult 时。那没起效。

我看到了控制台,似乎什么也没显示。

我不知道我做错了什么。

如何通过调用ActionResult从 ControllerAjax调用 Javascript 文件?

标签: javascriptajaxmodel-view-controller

解决方案


好吧,帮助我的初学者。这是我应付的解决方案。

首先,我了解到每个 ActionResult 都应该有一个 View(如果我没记错的话)。

所以,在我的AdminView.cshtml中,我创建了一个隐藏按钮。

  <button type="submit" id="submitLogout" name="button" value="logout" hidden>logout</button>

之后,在我的JSFILE

我删除了ajax。这首先是错误的。

   $("#logout").click(function () {
        swal({
            title: "ログアウト?",
            text: "アカウントからサインアウトしますか?",
            icon: "warning",
            buttons: true,
            dangerMode: true,
        })
            .then((willLogout) => {
                if (willLogout) {
                    $("#submitLogout").click();
                }
            });
    });

javascript中的这个功能是触发Controller中的隐藏按钮,.cshtml触发ActionResultController中的。

另外,在我的控制器中。这就是我所说的每个ActionResult人都必须有一个观点。

 public ActionResult AdminView(string button)
    {
        if (button == "logout")
        {
            FormsAuthentication.SignOut();
            Session.RemoveAll();
            Session.Abandon();
            return RedirectToActionPermanent("Login", "Login");
        }
        else
        {
            if (!(Session["UserInfo"] is UserModel))
            {
                return RedirectToActionPermanent("Login", "Login");
            }
            else
            {
                return View();
            }
        }
    }

string buttonActionResult 中的参数是name of the button您要触发的参数。如果触发成功,它会将按钮的值传递给参数string button


推荐阅读