I am trying to take the user to login page after cookies are cleared.
I am making a jquery call to my controller to clean the cookies but then I don't know how to redirect him to login page.
I am currently have this code inside my javascript:
function()
{
$.post('/Home/Action', function(result) {
});
window.location="login";
}
public Action()
{
cookie cleaning code;
}
but the problem is refreshing and cookie cleaning are done at the same time. I want to take the user after cookie cleaning.
Thanks
Why did you put window.location outside $.post callback? Try this:
function() {
$.post('/Home/Action', function(result) {
window.location.href = "login";
});
}
function CleanCookiesAndGotoLogin()
{
$.post('/Home/Action', function(result) {
//you put the relocation here so that it waits for the callback
window.location="/ControllerName/ActionName";
});
};
Related
I have developed an application in Asp.Net MVC with C# Programming Language and using code first Approach, The application is deployed and everything is working properly except a minor issue that i am facing.
When the session is expired it does not redirect the user to the main login page of the application, where i want that the application should redirect the user to the main login page while the session is expired.
How is it possible?
There are numerous examples for the functionality that you want to achieve, but I wanted to give you a basic scenario of how you would do a redirect to the login page when a session expires or the user logs out:
Assuming you have setup your session, when a user will logout, the controller will have a Logout method:
public ActionResult Logout()
{
Session.Abandon();
Session.Clear();
return RedirectToAction("LoginPage", "Login");
}
This would destroy the session variables and redirect the user to the Login page.
Now when a session expires, you can do something like this:
public ActionResult SessionCheck()
{
string message = string.Empty;
if (Session["UserName"] == null)
{
message = "Session expired. Please Login again";
}
return Json(message, JsonRequestBehavior.AllowGet);
}
You can check for this method throughout your program using AJAX or you could use SessionState.
I prefer to use AJAX so I am giving you a simple example:
function IsSessionActive()
{
var url ="/Login/SessionCheck";
var param = {};
param = JSON.stringify(param);
var result = getResultPost(url, param);
if (result != "")
{
alert("Session has expired, Please login again");
//Redirect Here
window.location="#Url.Action("LoginPage", "Login")";
return true;
}
}
function getResultPost(url, param) {
var result;
$.ajax({
url: url,
type: "POST",
async: false,
dataType: "json",
data: param,
contentType: "application/json; charset=utf-8",
success: function (data, textStatus) {
result = data;
},
error: function (e) {
result = "Error";
}
});
return result;
}
And finally call this in your View like:
$(document).ready(function () {
if (IsSessionActive()) return false;
})
This will check for the session on every page that you call this method and if the session is expired, it will alert the user and redirect to the Login page. You can customize your own styles like a modal or customized alert box to show the user that their session has expired. I hope this helps.
I want to redirect my page after 2 minutes of inactivity, for this I am using the below code to ping the controller every 2.5 minutes and if the session has expired I redirect to the original login page:
`<script language="javascript" type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript" type="text/javascript">
var ReqTime =#Session.Timeout
ReqTime = ReqTime * 60 * 1000 + (.5 * 60 * 1000);
$(function () {
setInterval(CheckSession, ReqTime);
});
function CheckSession() {
$.post('#Url.Action("SessionInfo","Home")', null, function () {
console.log("Time");
});
}
</script>
Controller:
public ActionResult SessionInfo()
{
if (Session["LoginUserName"]==null)
{
return RedirectToAction("Index","Home");
}
}
This code does not re-direct to the Home/Index. Can you tell me where I'm going wrong?
Try using Javascript instead ,since redirect from server side need a post back
You can check session by controller and return a value to figure out if session end or not
function CheckSession() {
$.ajax({
type: "GET",
url: "#Url.Action("SessionInfo", "Home")"
}).done(function (data) {
if (data === true) {
window.location.href = "#Url.Action("Index", "Home")";
}
}).fail(function (e) {
alert('Error');
});
}
Controller
public JsonResult SessionInfo()
{
if (Session["LoginUserName"] == null)
{
return Json(true, JsonRequestBehavior.AllowGet);
}
return Json(false, JsonRequestBehavior.AllowGet);
}
This code for explaining
By making those session checking ajax request you just extend life-span of the user session.
If you would like to inform browser that user session has end I recommend to implement a SignalR service to have direct communication ( push capability ) between server and the browser ( realtime ).
Implement a SignalR service,
Create a session_end method in your global.asax file, in the session_end send a message to user browser that your session has end.
Just it
I have a mvc project, what I want to do is this:
I am sending an ajax request from my JS script. After processing it I want to redirect to a page with a model.
Now I tried sending a form as the ajax response and submit it like so:
sb.Append("<html>");
sb.AppendFormat(#"<body onload='document.forms[""form""].submit()'>");
sb.AppendFormat("<form name='form' action='{0}' method='post'>", "url..");
sb.AppendFormat("<input type='hidden' name='result' value='{0}'>", val1);
.....
And on the JS:
success: function (result) {
var form = $(result);
$(form).submit();
}
But this way i need to specify each post param, I want to send the entire model object.
How can I do that?
Edit
Full steps:
1.Using an MVC APP.
2.I submit button in my view which redirects the user to my JS code.
3.Js code sends an Ajax request to a MVC page called 'Transaction'.
4.C# code doing some actions and now I need to redirect the usr to a page named EOF with ALOT of post params, thats why I want to pass it as a ViewModel.
As you are using ajax, you could return the URL from your action and have it redirected in javascript:
Controller
public ActionResult Transaction()
{
// Do stuff
return Json(new { success = true, redirecturl = Url.Action("RedirectedAction") });
}
Then add something like this to your success handler in javascript:
Javascript (within your success handler)
success: function (result) {
if (result.success == true)
{
window.location = result.redirecturl;
}
}
You can try this:
public ActionResult YourMethod(string param)
{
//what ever you want to do with reference no
return View("EOF");
// or, if you want to supply a model to EOF:
// return View("EOF", myModel);
}
I want to redirect from one page to another page in ASP.NET MVC 3.0 using JavaScript/jQuery/Ajax. On button click event I have written JavaScript code like below.
function foo(id)
{
$.post('/Branch/Details/' + id);
}
My controller code is like this:
public ViewResult Details(Guid id)
{
Branch branch = db.Branches.Single(b => b.Id == id);
return View(branch);
}
When I click on a button it is calling the Details action inside BranchController, but it doesn't return to the Details view.
I didn't get any error or exception. It's showing status 200 OK in Firebug. What is wrong in my code and how can I redirect to the Details view page?
You are not subscribing to any success callback in your $.post AJAX call. Meaning that the request is executed, but you do nothing with the results. If you want to do something useful with the results, try:
$.post('/Branch/Details/' + id, function(result) {
// Do something with the result like for example inject it into
// some placeholder and update the DOM.
// This obviously assumes that your controller action returns
// a partial view otherwise you will break your markup
});
On the other hand if you want to redirect, you absolutely do not need AJAX. You use AJAX only when you want to stay on the same page and update only a portion of it.
So if you only wanted to redirect the browser:
function foo(id) {
window.location.href = '/Branch/Details/' + id;
}
As a side note:
You should never be hardcoding urls like this. You should always be using url helpers when dealing with urls in an ASP.NET MVC application. So:
function foo(id) {
var url = '#Url.Action("Details", "Branch", new { id = "__id__" })';
window.location.href = url.replace('__id__', id);
}
This could be done by using a hidden variable in the view and then using that variable to post from the JavaScript code.
Here is my code in the view
#Html.Hidden("RedirectTo", Url.Action("ActionName", "ControllerName"));
Now you can use this in the JavaScript file as:
var url = $("#RedirectTo").val();
location.href = url;
It worked like a charm fro me. I hope it helps you too.
You can use:
window.location.href = '/Branch/Details/' + id;
But your Ajax code is incomplete without success or error functions.
// in the HTML code I used some razor
#Html.Hidden("RedirectTo", Url.Action("Action", "Controller"));
// now down in the script I do this
<script type="text/javascript">
var url = $("#RedirectTo").val();
$(document).ready(function () {
$.ajax({
dataType: 'json',
type: 'POST',
url: '/Controller/Action',
success: function (result) {
if (result.UserFriendlyErrMsg === 'Some Message') {
// display a prompt
alert("Message: " + result.UserFriendlyErrMsg);
// redirect us to the new page
location.href = url;
}
$('#friendlyMsg').html(result.UserFriendlyErrMsg);
}
});
</script>
<script type="text/javascript">
function lnkLogout_Confirm()
{
var bResponse = confirm('Are you sure you want to exit?');
if (bResponse === true) {
////console.log("lnkLogout_Confirm clciked.");
var url = '#Url.Action("Login", "Login")';
window.location.href = url;
}
return bResponse;
}
</script>
check the code below this will be helpful for you:
<script type="text/javascript">
window.opener.location.href = '#Url.Action("Action", "EventstController")', window.close();
</script>
Im new to jquery and stuck with what i want to achieve.
Heres what I want to do using jquery and asp.net mvc.
click a submit button
this calls an action method called LogOn in the controller Account
if the call allows users to log in succesfully redirect to a url (sepecified by LogOn)
if it fails replace a div(with id="error") with "sorry error occured"
so far I tried this:
$("#submit")
.button()
.click(function () {
$.ajax({
type: "POST",
url: "Account/LogOn",
dataType: "json",
success: function (data, textStatus) {
if (data.redirect) {
// data.redirect contains the string URL to redirect to
window.location.href = data.redirect;
}
else {
// data.form contains the HTML for the replacement form
$("#error2").replaceWith(data.error);
}
}
});
});
how do I construct the relevant bits in the action method? to make this work?
and is the jquery code ok? i suspect prob not.
Thanks
If you want to redirect asp.net page at same directory , you can by Jquery/Java script by this :
$("#ctl00_iframecontent_BtnCancle").click(function () {
window.location = "IncSLAList.aspx?bi=37";
});
and
To redirect to Another page of project , can use :
window.location.href = "http://ImageUpload/Welcome.aspx?
Your jQuery is almost correct:
Don't call .button() (unless you're using jQuery UI and want to do that)
Add return false; at the end of the click handler to prevent the browser from submitting normally.
In the action, you would either return Json(new { redirect = str }) or return Json(new { error = str }).