I inherited an MVC app with jQuery and Kendo. Most of the controller actions have the [Authorize] attribute and it handles the redirection to the Login page nicely if the user is not already authenticated.
However, there's one feature that requires some additional information before the action is invoked. So, when the button for that feature is clicked, a Kendo window is displayed asking the user for a DateTime input. Then the action is called with that extra piece of input data, and the user is sent to another page after the action completes with the result of that action.
Here's the simplified code flow:
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);
}
});
This works fine if the user is already logged in. But if the user is not already logged in, here's what happens:
How can I fix this where the Javascript code can detect whether the user is logged in or not, and direct him to the Login page instead?
I do not want to hide the button if the user is not authenticated. I want to let the user be able to click on the button, but get redirected instead.
Thanks for any help!
You can mix server side code and javascript code to checking weather user is logged in or not.
<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>
Edit: If you want pus your JS code in external file you have to put your code inside a function then pass a bool value to the function which indicate whether user is authenticated or not.
External 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';
}
}
}
and inside your html page call that function:
<script>
$(function() {
handleButtonClick(@User.Identity.IsAuthenticated);
});
</script>