javascript - 在 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 文件?
解决方案
好吧,帮助我的初学者。这是我应付的解决方案。
首先,我了解到每个 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
触发ActionResult
Controller中的。
另外,在我的控制器中。这就是我所说的每个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 button
ActionResult 中的参数是name of the button
您要触发的参数。如果触发成功,它会将按钮的值传递给参数string button
。
推荐阅读
- typescript - Angular2 Typescript 静态构造函数声明
- java - 嵌入式H2数据库:没有执行sql文件
- angular - 动态创建 formGroup 时 control.setParent 不是函数
- r - 用 R 模拟比赛结果
- html - 输入类型提交值受到 css 转换属性的影响
- php - 在 Laravel webapp 中实现负载均衡器时出现太多请求错误
- javascript - Cordova android - 键盘覆盖输入字段
- fasttext - fasttext 的句子向量
- python - 读取多个 CSV 文件并水平连接它们
- html - 使用 git bash 在 Windows 7 中打开一个 html 文件