MaintainScrollPositionOnPostback is not working? - c#

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>/>

Related

Disabling backbutton of browser in 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>

Async postback not working

I'm using this gauge in my contentplaceholder.
http://www.dariancabot.com/projects/jgauge_wip/
MyControl.ascx:
<link rel="stylesheet" href="Scripts/jgauge.css" type="text/css" />
<script type="text/javascript" src="Scripts/jquery-1.8.0.js"></script>
<script language="javascript" type="text/javascript" src="Scripts/jgauge-0.3.0.a3.js"></script>
<script language="javascript" type="text/javascript" src="Scripts/jQueryRotate.2.2.js"></script>
<script language="javascript" type="text/javascript" src="Scripts/excanvas.min.js"></script>
<div id="<%=this.ClientID%>_ctl" class="jgauge" ></div>
<script type="text/javascript">
$(document).ready(function () {
var isPostBack = <%= Page.IsPostBack ? "true" : "false" %>;
if(isPostBack == "true")
{
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
prm.add_endRequest(onEndRequest);
}
else{
var <%=this.ClientID%>_ctl;
<%=this.ClientID%>_ctl = new jGauge();
<%=this.ClientID%>_ctl.id = '<%=this.ClientID%>_ctl';
<%=this.ClientID%>_ctl.init();
}
});
function EndRequestHandler(sender, args){
var <%=this.ClientID%>_ctl;
<%=this.ClientID%>_ctl = new jGauge();
<%=this.ClientID%>_ctl.id = '<%=this.ClientID%>_ctl';
<%=this.ClientID%>_ctl.init();
}
</script>
In MyPage.aspx: (Contains dynamically created table having several such controls. putting the generated table on placeholder)
<asp:UpdatePanel ID="up1" runat="server">
<ContentTemplate>
<asp:PlaceHolder id="phMain" runat="server" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="myBtn" />
</Triggers>
</asp:UpdatePanel>
<asp:Button ID="myBtn" runat="server" Text="Refresh" />
I have script manager on master page:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="true"></asp:ScriptManager>
But after async postback (hitting 'myBtn'), gauge disappears. Please Help. Trying to solve it since couple of days.
I was able to solve this with by going:
$(document).ready(function () {
Sys.WebForms.PageRequestManager.getInstance()
.add_endRequest(<%=this.ClientID%>_ctlEndRequestHandler);
var <%=this.ClientID%>_ctl;
<%=this.ClientID%>_ctl = new jGauge();
<%=this.ClientID%>_ctl.id = '<%=this.ClientID%>_ctl';
<%=this.ClientID%>_ctl.init();
});
function <%=this.ClientID%>_ctlEndRequestHandler(sender, args){
var <%=this.ClientID%>_ctl;
<%=this.ClientID%>_ctl = new jGauge();
<%=this.ClientID%>_ctl.id = '<%=this.ClientID%>_ctl';
<%=this.ClientID%>_ctl.init();
}
The only real difference is that the postback checks are no longer taking place. Your underlying problem is that $(document).ready will not fire on partial postbacks, which means that isPostBack is never actually getting set to true. Because of this, Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler); was never executing, meaning that your EndRequestHandler never ran.
Edit
The other issue is that naming the method EndRequestHandler is guaranteed to cause problems if you have more than one of the control at the same time. To get around this, I appended <%=this.ClientID%>_ctl to the name of EndRequestHandler to ensure it was unique.
More info:
How do I use a jQuery $(document).ready and an ASP.NET UpdatePanel together?
http://encosia.com/document-ready-and-pageload-are-not-the-same/

images are not being displayed

I have done the following jquery function which is supposed to change dynamically images. The problem is that it is doing nothing as if there is no jquery function. The jquery function is being totally ignored without even enter in the function.
The coding I used is the one below;
<asp:Content ID="Content1" ContentPlaceHolderID="stylesPlaceHolder" runat="server">
<script type="text/javascript">
var index = 0;
var images = [
'child.jpg',
'girl.gif',
'sponsor.jpg'
];
$('Image1').attr('src', 'Resources/ChildrenImages/' + images[0]);
setInterval(change_image, 5000);
$(document).ready(function() {
index++;
if (index >= images.length) index = 0;
$('Image1').attr('src', 'Resources/ChildrenImages/' + images[index]);
});
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="contentPlaceHolder" runat="server">
<div>
<asp:Image ID="Image1" runat="server" Height="198px" Width="225px"/>
</div>
</asp:Content>
Any suggestions to what the problem could be?
The problem is that you're probably not selecting anything:
$('Image1')
should be
$('#Image1')
Please note also that there's a difference between the ID that you set and the rendered one (which is ClientID in ASP.net), so you should either use:
$('img[id$="Image1"]') //Select an image whose ID ends with 'Image1'
Or reference the ClientID property in your script.
Set the ClientIDMode property of the Image to Static, and as per the other answer the JQuery Identifier should start with a #, #Image1.

The Controls collection cannot be modified because the control contains code blocks

This is a bit different to all the other questions as they all seem to refer to the head content specifically. With this one, I have a user control with the following placeholder:
<asp:PlaceHolder runat="server" ID="DiscussIncludes">
<script>
var OnLastPage = <asp:Literal runat="server" ID="OnLastPageJS" />;
var AJAXWait = false;
var MinChars = <%=Settings.MinimumCommentChars%>;
var AJAXURL = "<%=ResolveClientUrl("~/Handlers/DiscussAjaxHandler.ashx")%>";
var CurrUsername = "<%=ThisUser.Username %>";
var GravHash = "<asp:Literal runat="server" ID="GravJSRef" />";
var RelURL = "<%=ResolveClientUrl("~/users/")%>";
var Anch = "<%=Anchor.ToString()%>";
var MyRep = "<%=MyRepString%>";
var CurrReportID = 0;
var LastPageURL = "<asp:Literal runat="server" ID="JSLastPageURL" />";
var AllowedChars = <%=Settings.MaxCommentChars %>;
</script>
<script src="<%=CommonFunctions.AllocateStaticPath("/js/Discuss.js?v=" + Settings.JSVersionID)%>"></script>
<script src="<%=CommonFunctions.AllocateStaticPath("/js/BlockUI.js?v=" + Settings.JSVersionID)%>"></script>
</asp:PlaceHolder>
In the code behind I have:
ContentPlaceHolder FooterControl = (ContentPlaceHolder)Page.Master.FindControl("JavascriptIncludes");
FooterControl.Controls.Add(DiscussIncludes);
This throws the error:
The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
On the FooterControl.Controls.Add(DiscussIncludes); line. I've tried changing all the <%= to <%# within the placeholder but no luck.
One point to note is this control works fine on all my other pages. Any ideas what would be causing this?
Nothing in this control is causing the problem -- if it happens when you add the control to a particular environment and only that environment the that points at the issue. What is going on on the complaining page?
I tried the following on my system and it seems to be working...
<asp:PlaceHolder runat="server" ID="DiscussIncludes">
<script type="text/javascript">
var path = <%=Common.path%>;
</script>
<script type="text/javascript" src='<%=Common.GetScriptPath("jquery-1.4.1-vsdoc.js")%>'></script>
<asp:PlaceHolder runat="server" ID="JsIncludes">
</asp:PlaceHolder>
</asp:PlaceHolder>
on code behind..
LiteralControl include = new LiteralControl(string.Format("<script src='{0}'></script>", Common.GetScriptPath("jquery-1.4.1.min.js")));
JsIncludes.Controls.Add(include);
I get the exception if i try to add the control to DiscussIncludes. However if add the control to JsIncludes it works. JsIncludes control is a child placeholder of DiscussIncludes.

How to use multiple instances of a usercontrol (with jquery) on the same page

I've been working on an usercontrol with a jquery timer in it. At first I had the jquery within the usercontrol. But when I add 2 of those controls to my page the second usercontrol isn't showing it's data very well.
Now I've put the jquery into the mainpage and the usercontrol only uses the id's of the jquery.
Here is my usercontrol:
<%# Control Language="C#" AutoEventWireup="true" CodeFile="WebUserControl.ascx.cs"
Inherits="WebUserControl" %>
<style type="text/css">
#mainpanel
{
width: 145px;
height: 123px;
}
</style>
<div id="mainpanel">
<div>
test</div>
<div id="shortly" style="background-color: #FFFFFF">
</div>
<button id="resetButton">
Reset
</button>
</div>
Mainpage:
<%# Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%# Register Src="WebUserControl.ascx" TagName="WebUserControl" TagPrefix="uc1" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>hoi</title>
<script src="Scripts/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="Scripts/jquery-ui-1.8.1.custom.min.js" type="text/javascript"></script>
<link href="Css/jquery-ui-1.8.1.custom.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script type="text/javascript" src="Scripts/jquery.countdown.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$(function() {
$("#mainpanel");
});
shortly = new Date();
shortly.setSeconds(shortly.getSeconds() + 5.5);
$('#shortly').countdown({ until: shortly,
onExpiry: liftOff, layout: '{sn}',
});
$('#resetButton').click(function () {
$('#mainpanel').effect("highlight", {}, 700 );
$('#shortly').effect("highlight", {}, 700 );
shortly = new Date();
shortly.setSeconds(shortly.getSeconds() + 5.5);
$('#shortly').countdown('change', { until: shortly });
});
function liftOff() {
// refresh the page
window.location = window.location;
}
});
</script>
</head>
<body>
<uc1:WebUserControl ID="WebUserControl1" runat="server" />
<uc1:WebUserControl ID="WebUserControl2" runat="server" />
</body>
</html>
But still my usercontrols are acting weird, now my question is: "How can I make the SAME usercontrols work properly on ONE page?"
Both of those use the same jquery code but the buttons etc. should only work within the usercontrol itself.
As David suggests, seeing as you are repeating the user controls and you are explicitly setting their id, you will end up with several controls that share the same id on the page. I imagine that $("#someid") will return the first element in the page and not necessarily the one you really wanted.
David is suggesting adding CSS classes to the elements in your user control (this has nothing to do with jQuery - although the jQuery you write will refer to them).
For example
<%# Control Language="C#" %>
<div class="mainpanel">
<div>
test
</div>
<div class="shortly">
??
</div>
<button class="resetButton">
Reset
</button>
</div>
[PS. note that you should probably remove your CSS from your user control as repeating each time the control appears on the page is bad practise e.g. include this either in your main page or a separate CSS file]
<style type="text/css">
#mainpanel
{
width: 145px;
height: 123px;
}
#shortly
{
background-color: #FFFFFF
}
</style>
Your script can then be something like
$(function () {
// function that does something exciting?
var liftOff = function() {
// ....
};
// Get a date that is some (short) time in the future
var getDeadline = function() {
var shortly = new Date();
shortly.setSeconds(shortly.getSeconds() + 5.5);
return shortly;
};
// Attach click handler to all our buttons
$("div.mainpanel button.resetButton").click(function(event){
// I am assuming that you will not be nesting these controls?
var $mainpanel = $(this).parents("div.mainpanel") // this will find the mainpanel div that contains the pressed button
.effect("highlight", {}, 700 );
$("div.shortly", $mainpanel) // this will find any div with the class = shortly inside mainpanel
.countdown('change', { until: getDeadline() });
});
// Start all countdowns going on page load
$('#shortly').countdown({
until: getDeadline(),
onExpiry: liftOff,
layout: '{sn}'
});
});
Your user control is using id="" on elements. Id's must be unique within a single html page. If you need to attach css styles or something to query via jquery, you need to use classes instead of id's so that the second control doesn't break the convention that id's must be unique.

Categories

Resources