我继承了一个带有 jQuery 和 Kendo 的 MVC 应用程序。大多数 Controller 操作都具有 [Authorize] 属性,如果用户尚未经过身份验证,它可以很好地处理到登录页面的重定向。
但是,有一项功能在调用操作之前需要一些附加信息。因此,当单击该功能的按钮时,会显示一个 Kendo 窗口,要求用户输入日期时间。然后使用该额外的输入数据调用该操作,并在该操作完成后将用户发送到另一个页面并显示该操作的结果。
这是简化的代码流程:
btnClicked_Listener{
// Pop-up Kendo window for DateTime input
// Get URL for action (@Url.Action("MyAction1", "MyController", new { date = [DateTime input] })
$.ajax({
datatype: 'json',
url: finalUrl,
cache: false,
success: function (result) {
window.location.href = window.location.origin + '/MyController/MyAction2?planId=' + result;
},
error: function (xhr, error, message) {
handleError(xhr, error, message);
}
});
如果用户已经登录,则效果很好。但如果用户尚未登录,则会发生以下情况:
- 用于日期时间输入的 Kendo 窗口弹出窗口。
- 显示登录页面(因为 MyAction1 具有 [Authorize] 属性)。
- 用户登录。
- 页面“/MyController/MyAction2?planId=”无效,因为 MyAction1 永远不会被命中,因此 result=null。
如何解决这个问题,让 Javascript 代码可以检测用户是否登录,并将其引导至登录页面?
如果用户未经过身份验证,我不想隐藏该按钮。我想让用户能够单击该按钮,但会被重定向。
感谢您的帮助!
最佳答案
您可以混合服务器端代码和 JavaScript 代码来检查天气用户是否登录。
<script>
btnClicked_Listener
{
@if (User.Identity.IsAuthenticated)
{
<text>
// Pop-up Kendo window for DateTime input
// Get URL for action (@Url.Action("MyAction1", "MyController", new {date = [DateTime input]})
$.ajax({
datatype: 'json',
url: finalUrl,
cache: false,
success: function (result) {
window.location.href = window.location.origin + '/MyController/MyAction2?planId=' + result;
},
error: function (xhr, error, message) {
handleError(xhr, error, message);
}
});
</text>
}
else
{
<text> window.location.href = 'Login page url' </text>
}
}
</script>
编辑:如果您想将 JS 代码放入外部文件中,则必须将代码放入函数中,然后将 bool 值传递给该函数,以指示用户是否经过身份验证。
外部JS
function handleButtonClick(isAuthenticated) {
btnClicked_Listener
{
if (isAuthenticated) {
// Pop-up Kendo window for DateTime input
// Get URL for action (@Url.Action("MyAction1", "MyController", new {date = [DateTime input]})
$.ajax({
datatype: 'json',
url: finalUrl,
cache: false,
success: function(result) {
window.location.href = window.location.origin + '/MyController/MyAction2?planId=' + result;
},
error: function(xhr, error, message) {
handleError(xhr, error, message);
}
});
} else {
window.location.href = 'Login page url';
}
}
}
并在你的 html 页面中调用该函数:
<script>
$(function() {
handleButtonClick(@User.Identity.IsAuthenticated);
});
</script>
关于Javascript - 单击按钮时,如果未经过身份验证,则重定向到登录页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24617839/