我继承了jQuery和Kendo的MVC应用程序。大多数控制器操作都具有[Authorize]属性,如果用户尚未经过身份验证,它会很好地处理重定向到Login页面。
但是,在调用操作之前,有一项功能需要一些额外的信息。因此,当单击该功能的按钮时,将显示一个Kendo窗口,询问用户输入DateTime。然后使用额外的输入数据调用操作,并在操作完成后将用户发送到另一个页面,并显示该操作的结果。
这是简化的代码流程:
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);
}
});
如果用户已经登录,这样可以正常工作。但如果用户尚未登录,则会发生以下情况:
如何解决这个问题,Javascript代码可以检测用户是否已登录,并将其引导至“登录”页面?
如果用户未经过身份验证,我不想隐藏按钮。我希望让用户能够点击按钮,但改为重定向。
感谢您的帮助!
答案 0 :(得分:2)
您可以将服务器端代码和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>