Disabling backbutton of browser in C# - c#

<script type="text/javascript">
{
function DisableBackButton() {
window.history.forward()
}
DisableBackButton();
window.onload = DisableBackButton;
window.onpageshow = function (evt) { if (evt.persisted) DisableBackButton() }
window.onunload = function () { void (0) }
}
</script>
I am using the following code in the master page to diable the back button.
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.UtcNow.AddHours(-1));
Response.Cache.SetNoStore();
Response.ExpiresAbsolute = DateTime.Now.AddDays(-1d);
Response.Expires = -1500;
Response.CacheControl = "no-cache";
Page.Response.Cache.SetCacheability(HttpCacheability.NoCache);
I have a master page in that logout button is there once user click on that user will be redirected to logout page. This is working fine and once I am clicking on back button it is taking me to the last page I browsed. Even I tried with JavaScript.
I am creating timing out the session after 5 minutes. When session expires user will be redirected to session expiry page there also backbutton is taking me to the last page browsed.

Here this JavaScript functionality will work in all browsers and prevent users navigating back to previous page by hitting on browser back button check below piece of JavaScript code
<script type="text/javascript" language="javascript">
function DisableBackButton() {
window.history.forward()
}
DisableBackButton();
window.onload = DisableBackButton;
window.onpageshow = function(evt) { if (evt.persisted) DisableBackButton() }
window.onunload = function() { void (0) }
</script>
We need to place above script in header section of a page wherever we need to prevent users navigate back to another page by using browser back button.
I will explain our requirement with an example I have two pages Defaul1.aspx and Default2.aspx now I will redirect from Default1.aspx page to Defaul2.aspx page. After come from Defaul1.aspx page to Default2.aspx if I try to navigate back to Default1.aspx page from Defaul2.aspx then I want prevent user navigate back to previous page (Defaul1.aspx). To achieve this functionality place above JavaScript function in header section of required page.
After add our JavaScript functionality to our page that code will be like this
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Disable Browser Back buttons</title>
<script type="text/javascript" language="javascript">
function DisableBackButton() {
window.history.forward()
}
DisableBackButton();
window.onload = DisableBackButton;
window.onpageshow = function(evt) { if (evt.persisted) DisableBackButton() }
window.onunload = function() { void (0) }
</script>
</head>
<body >
<form id="form1" runat="server">
<div>
First Page
</div>
<div>
<asp:Button id="btnFirst" runat="server" Text="Go to First Page" PostBackUrl="~/Default.aspx" />
<asp:Button ID="btnSecond" runat="server" Text="Go to Second Page" PostBackUrl="~/Default2.aspx" />
<asp:Button ID="btnThree" runat="server" Text="Go to Third Page" PostBackUrl="~/Default3.aspx" />
</div>
</form>
</body>
</html>
We can also achieve this by disabling browser caching in code behind write the following lines of code in Page_Init event or Page_Load event and don’t forgot to add namespace using System.Web; because HttpCacheability related to that namespace.
protected void Page_Init(object sender, EventArgs e)
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));
Response.Cache.SetNoStore();
}
We need to place this code in a page wherever we need to disable browser back button

<script type="text/javascript" language="javascript">
window.onload = function () {
noBack();
}
function noBack() {
window.history.forward();
}
</script>
<body onpageshow="if (event.persisted) noBack();">
</body>
Hello,
You can do it like this,
Implement this code in master page
I have implemented this and it worked for me..

<script language="JavaScript">
this.history.forward(-1);

Redirect to Logout.aspx page on clicking "logout"
Add a new page as Logout.aspx with following body content.
Please wait. You are Logging out.
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<asp:Timer ID="Timer1" runat="server" Interval="1000" ontick="Timer1_Tick">
</asp:Timer>
add javascript as below
function noBack() {
window.history.forward()
}
noBack();
window.onload = noBack;
window.onpageshow = function (evt) { if (evt.persisted) noBack(); }
window.onunload = function () { void (0); }
Logout.aspx.cs
protected void Page_Load(object sender, EventArgs e)
{
Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1));
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Cache.SetNoStore();
}
protected void Timer1_Tick(object sender, EventArgs e)
{
Response.Redirect("Login.aspx"));
}
Source : http://geekswithblogs.net/Frez/archive/2010/05/18/back-button-issue-after-logout-in-asp.net.aspx

When user clicks logout button, you should write single line to clear the session.
Session.Abondon();
and navigate to logout page or login page. So that once user clicks logout button, he cannot go back becaause his session was cleared.

To disable the back button of the browser write the below code at master page header part as
<script language="JavaScript" type="text/javascript">
window.history.forward();
</script>

<script type="text/javascript">
function DisableBackButton() {
window.history.forward()
}
DisableBackButton();
window.onload = DisableBackButton;
window.onpageshow = function (evt) { if (evt.persisted) DisableBackButton() }
window.onunload = function () { void (0) }
</script>

Related

MaintainScrollPositionOnPostback is not working?

I have a page with two drop down lists (ddlA and ddlB)
Once the user selects an item from ddlA, it will populate items in ddlB
I have auto post-back turned on for ddlA.
and since I wanted to maintain the scroll position, i turned on the MaintainScrollPositionOnPostBack to true like this in the page load method. :
this.MaintainScrollPositionOnPostBack = true;
But this doesn't seem to fix the issue.
Is there a workaround to fix the problem.?
-- UPDATE --
I added this js code to the page and now the problem is that the autopost back is never happening..
<script type="text/javascript">
var xPos, yPos;
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(BeginRequestHandler);
prm.add_endRequest(EndRequestHandler);
function BeginRequestHandler(sender, args) {
xPos = $get('scrollDiv').scrollLeft;
yPos = $get('scrollDiv').scrollTop;
}
function EndRequestHandler(sender, args) {
$get('scrollDiv').scrollLeft = xPos;
$get('scrollDiv').scrollTop = yPos;
}
</script>
Am i adding the js code incorrectly? I found it here
Try to add this to the Page directive in your ASPX file and test it that route.
<%# Page Title="" Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" MaintainScrollPositionOnPostback="true" Inherits="_Default" %>
I couldn't get MaintainScrollPositionOnPostback to work for me no matter what I tried. Based on this answer (https://stackoverflow.com/a/27505983) and a comment underneath it, I tried the following code which worked for me. This will only work if you have an ASP.NET ScriptManager (i.e. MicrosoftAjax.js) on your page. You also need JQuery added to your page. Add the below code to your .aspx file somewhere underneath asp:ScriptManager tag.
<asp:HiddenField runat="server" ID="hfPosition" Value="" />
<script type="text/javascript">
$(function () {
var positionField = $("#<%=hfPosition.ClientID%>");
window.onscroll = function () {
var position = $(window).scrollTop();
positionField.val(position);
};
});
function pageLoad() {
var positionField = $("#<%=hfPosition.ClientID%>");
var position = parseInt(positionField.val());
if (!isNaN(position)) {
$(window).scrollTop(position);
}
};
</script>
Basically we are holding the scroll position inside the value of a hidden field called hfPosition. Whenever the page is scrolled, the value will be updated. Then when a postback happens pageLoad() will automatically be called and will get the value of hfPosition and scroll to that value.
Including the ScriptManager and JQuery, my final code snippet looked something like this:
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<script src="../Scripts/jquery-3.3.1.min.js" type="text/javascript"></script>
<asp:HiddenField runat="server" ID="hfPosition" Value="" />
<script type="text/javascript">
$(function () {
var positionField = $("#<%=hfPosition.ClientID%>");
window.onscroll = function () {
var position = $(window).scrollTop();
positionField.val(position);
};
});
function pageLoad() {
var positionField = $("#<%=hfPosition.ClientID%>");
var position = parseInt(positionField.val());
if (!isNaN(position)) {
$(window).scrollTop(position);
}
};
</script>/>

JS function calling from the code behind Issue

I have a JS function (Show alert box), and have a link button in ASP page, On click event from code behind for this link button I want to call this function and then redirect to certain page.
ASP Code
<script type="text/javascript" language="javascript">
function myFunction() {
// executes when HTML-Document is loaded and DOM is ready
alert("document is ready!");
}
</script>
<div>
<asp:LinkButton ID="lnkbtnChangePassword" runat="server" Text="Change Passwrod" OnClick="lnkbtnChangePassword_Click" ></asp:LinkButton>
</div>
C# Code
protected void lnkbtnChangePassword_Click(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "myFunction()", true);
Response.Redirect("myPage.aspx");
}
Here when I click on the link button, it simply don't display the alert box/window and redirect to the page.
You should use LinkButton.ClientClick instead of LinkButton.Click event.
Click event is handled on server. When user clicks the button, page is posted back to server and code is executed on server side.
ClientClick event is really a name of JavaScript function which should be executed.
You should probably do something like this:
<asp:LinkButton ID="lnkbtnChangePassword" runat="server" Text="Change Passwrod" OnClientClick="showMyAlertAndSubmit()"></asp:LinkButton>
<script type="text/javascript">
function showMyAlertAndSubmit(){
alert("Your password is being changed");
// submit your form
}
</script>
Why your current code doesn't work
You currently send script for showing a message, and redirect at the same time. This means that browser receives instructions to show a message and to redirect, and it redirects the user before showing the message. One approach could be to redirect from client side. For example:
protected void lnkbtnChangePassword_Click(object sender, EventArgs e)
{
ClientScript.RegisterStartupScript(this.GetType(), "CallMyFunction", "myFunction()", true);
}
and on client side
function myFunction() {
// show your message here
// do other things you need
// and then redirect here. Don't redirect from server side with Response.Redirect
window.location = "http://myserver/myPage.aspx";
}
Other options
Since you need to first perform checks on server side before saving data and redirecting, you can use ajax to call server without performing postback.
Remove Click handler, and only use ClientClick:
function myFunction() {
$.ajax({
type: "POST",
url: "myPage.aspx/MyCheckMethod",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
ShowAlert();
window.location = "http://myserver/mypage.aspx";
}
});
}
For more details please check this tutorial.
Change your code like this:
ASP Code
<script type="text/javascript" language="javascript">
function myFunction() {
// executes when HTML-Document is loaded and DOM is ready
alert("document is ready!");
}
</script>
<div>
<asp:LinkButton ID="lnkbtnChangePassword" runat="server" Text="Change Passwrod" OnClick="lnkbtnChangePassword_Click" OnClientClick="myFunction()" ></asp:LinkButton>
</div>
C# Code
protected void lnkbtnChangePassword_Click(object sender, EventArgs e)
{
Response.Redirect("myPage.aspx");
}
Change your javascript function to :
<script type="text/javascript" language="javascript">
function myFunction() {
// alert will stop js execution
alert("document is ready!");
// then reload your page
__doPostBack('pagename','parameter');
}
</script>
And call it from code-behind with this function :
protected void lnkbtnChangePassword_Click(object sender, EventArgs e)
{
//do your job here
//then call your js function
ScriptManager.RegisterStartupScript(this,this.GetType(), "CallMyFunction", "myFunction();", true);
}
What you're missing is waiting for JavaScript alert dialog to popup and then redirect to the page.
In order to do this you need to tell button to wait for JavaScript alert dialog to popup and then do the Server side work after.
ASPX:
<head runat="server">
<title></title>
<script type="text/javascript">
function alertBeforeSubmit() {
return alert('Document Ready');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button Text="Do" runat="server" ID="btnSubmit" OnClick="btnSubmit_Click" OnClientClick="return alertBeforeSubmit();" />
</div>
</form>
</body>
CS:
protected void btnSubmit_Click(object sender, EventArgs e)
{
Response.Redirect("Default.aspx");
}

How to call a javascript function before and after button click event call in asp.net

i have created "ButtonClick" function in ASP.NET as following:
<asp:Button ID="btnLogin" runat="server" Text="Login" CssClass="button" CausesValidation="true" onclick="btnLogin_Click"/>
i want to know, is it possible to call a javascript function before and after calling asp.net button click function...???
Thanks.
Yes it's possible, here is quick example:
Java script function to call.
<script type="text/javascript">
function clientValidate() {
alert("execute before");
return true;
}
function executeAfter() {
alert("execute after");
}
</script>
Here is snapshoot for button
<asp:Button ID="btnLogin" runat="server" Text="Login" CausesValidation="true" OnClientClick="clientValidate()" onclick="btnLogin_Click"/>
Notice property onClientClick="clientValidate()", it will be trigger script before button click on the server.
On the server side:
protected void btnLogin_Click(object sender, EventArgs e)
{
ScriptManager.RegisterClientScriptBlock(this, GetType(), "none", "<script>executeAfter();</script>", false);
}
Notice executeAfter();, it will trigger javascript execution after server event.
Don't forget to place <asp:ScriptManager runat="server"></asp:ScriptManager> in your aspx file.
Hope it help
put this on your page and make sure you have a scriptmanager. these codes will handle your pre & post postbacks.
var prm, postBackElement;
if (typeof Sys != "undefined") {
prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_initializeRequest(InitializeRequest);
prm.add_endRequest(EndRequest);
}
function InitializeRequest(sender, e) {
postBackElement = e.get_postBackElement();
if (postBackElement.id == "btnLogin") {
// before click codes
}
}
function EndRequest(sender, e) {
if (postBackElement.id == "btnLogin") {
// after click codes
}
}
Before:
<script type="text/javascript">
function executeBefore() {
alert("execute before");
}
</script>
<asp:Button ID="btnLogin" runat="server" Text="Login" CausesValidation="true" OnClientClick="executeBefore()" onclick="btnLogin_Click"/>
After:
<script type="text/javascript">
function executeAfter() {
alert("execute after ");
}
</script>
Add this code to your server side event:
Page.ClientScript.RegisterStartupScript(GetType(), "none", "<script>executeAfter();</script>", false);
If you don't have a master page, or are not using ajax, there is no need to add ScriptManager.
You can call Java scrip function before server side click using OnClientClick():
aspx(design)
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
function Test() {
alert('client click');
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button Text="btn" runat="server" ID="btn"
OnClick="btn_Click" OnClientClick="Test()" />
</div>
</form>
</body>
</html>
.cs
protected void btn_Click(object sender, EventArgs e)
{
Response.Write("Server Click");
}
First time you can call your javascript function in Button's OnClientClick event passing your function name.
<asp:Button ID="btnLogin" runat="server" Text="Login" CssClass="button" CausesValidation="true" onclick="btnLogin_Click" OnClientClick="return functionNAME();"/>
Second time, in your button click event btnLogin_Click call js as follow
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "script", "<script type='text/javascript'>functionNA();</script>", false);
For calling it before, you could consider using onload function, like this example:
<body onload="myFunction()">
For calling it afterwards, just link the button to execute JS onClick?
I don't think I quite understand your intentions.

Access the Label value on Page load in c# when value set through jQuery

I am posting this question again, maybe this time more accurate description.
The problem is , I am using jQuery to set the Label's text value and it works fine on browser, but when I want to save it to string, it does not save it. Here is the
front End Html Code.
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(window).load(function () {
var myNewName = "Ronaldo";
$('#<%= Label1.ClientID %>').text(myNewName);
});
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
</form>
</body>
</html>
And here is the Back End C# Code On Page Load
using System;
using System.Web.UI;
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
string mynameCheck = Label1.Text;
if (mynameCheck=="Ronaldo")
{
Response.Write("Yes Name is Fine");
}
else
{
Response.Write("Name's not Fine");
}
}
}
The result displayed is
Name's not Fine
Ronaldo
Seems like the string is still Null. Is there any problem of rendering??
label is not input type so you can not get changed values through jquery on server side. You can use hidden field for this purpose.
Your server side code (c#) can not access the form data until your client side code (HTML/Javascript) posts it.
Why do you want to the name already at the PageLoad event?
You could add a asp:Button with an attached onClick event handler to read the value of your asp:Label.
Labels do not maintain viewstate. The server will not post that information back to the server. You can try explicitly enabling the ViewState on your Label, but if that doesn't work, you will have to store that value in a hidden field.
First Call Page Load event and after that call JQuery Window.Load event.
So if you want to set any content in Label then you can do using onClientClick of button.
For ex.
<asp:Button ID="btn" runat="server" Text="Click me" OnClientClick="SetClientValues();" />
<script type="text/javascript">
function SetClientValues() {
var myNewName = "Ronaldo";
$('#<%= Label1.ClientID %>').text(myNewName);
}
</script>
At server side button event you can get Label values that sets at client side.
protected void btn_Click(object sender, EventArgs e)
{
string mynameCheck = Label1.Text;
if (mynameCheck=="Ronaldo")
{
Response.Write("Yes Name is Fine");
}
else
{
Response.Write("Name's not Fine");
}
}
It will print Yes Name is Fine
This should do it:
<script type="text/javascript">
$(window).load(function () {
if($('#<%= Txt1.ClientID %>').val() != "Ronaldo"){
var myNewName = "Ronaldo";
$('#<%= Txt1.ClientID %>').val(myNewName);
$('#<%= Label1.ClientID %>').text(myNewName);
$('#<%= Btn1.ClientID %>').click();
}
});
</script>
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<asp:TextBox ID="Txt1" runat="server" style="display:none"></asp:Label>
<asp:Button ID="Btn1" runat="server" style="display:none" Click="Btn1_Click"></asp:Label>
</form>
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
Label1.Text=Txt1.Text;
string mynameCheck = Label1.Text;
if (mynameCheck=="Ronaldo")
{
Response.Write("Yes Name is Fine");
}
else
{
Response.Write("Name's not Fine");
}
}
}
protected void Btn1_Click(object sender, EventArgs e)
{ }
Hope it helps :)

Asp.Net Static method to refresh page

I have a page that is hitting a webservice every 5 seconds to update the information on the page. I'm using the DynamicPopulateExtender from the Ajax Control Toolkit to just populate a panel with some text.
What I was wanting to do, is if a certain condition is met, to refresh the page completely.
Am I going to be able to do this in the current method that I have? here's my current stuff:
ASP.NET
<cc1:DynamicPopulateExtender ID="DynamicPopulateExtender1" runat="server"
ClearContentsDuringUpdate="true" TargetControlID="panelQueue" BehaviorID="dp1"
ServiceMethod="GetQueueTable" UpdatingCssClass="dynamicPopulate_Updating" />
Javascript
Sys.Application.add_load(function(){updateQueue();});
function updateQueue()
{
var queueShown = document.getElementById('<%= hiddenFieldQueueShown.ClientID %>').value;
if(queueShown == 1)
{
var behavior = $find('dp1');
if (behavior)
{
behavior.populate();
setTimeout('updateQueue()', 5000);
}
}
}
SERVER (C#)
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod]
public static string GetQueueTable()
{
System.Text.StringBuilder builder = new System.Text.StringBuilder();
try
{
// do stuff
}
catch (Exception ex)
{
// do stuff
}
return builder.ToString();
}
You can't do anything from your ASMX.
You can refresh the page from JavaScript by using a conventional page reload or by doing a postback that would perform server-side changes and then update via your UpdatePanel or, more simply, a Response.Redirect.
You can force a Postback from Javascript, see this Default.aspx page for a example:
Default.aspx
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<script type="text/javascript" language="javascript">
function forcePostback()
{
<%=getPostBackJavascriptCode()%>;
}
</script>
</head>
<body onload="javascript:forcePostback()">
<form id="form1" runat="server">
<div>
<asp:Label ID="Label1" runat="server" Text="Postbacking right now..."></asp:Label>
</div>
</form>
</body>
</html>
Default.aspx.cs
namespace ForcingApostback
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack) Label1.Text = "Done postbacking!!!";
}
protected string getPostBackJavascriptCode()
{
return ClientScript.GetPostBackEventReference(this, null);
}
}
}
On the client-side, under any condition, you could then call the forcePostback() Javascript function to force the Postback.

Categories

Resources