ASP.Net : Need to run javascript on update panel load completed - asp.net

I need to run a javascript function when the update panel is loaded completely(I want to scroll), and not on initial page load.
Please suggest.
Thanks

This is the way to get the end Event after the update.
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(EndRequest);
function EndRequest(sender, args) {
}
</script>

Untested
<script type="text/javascript">
var app = Sys.Application;
app.add_init(ApplicationInit);
function ApplicationInit(sender) {
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (!prm.get_isInAsyncPostBack())
{
prm.add_pageLoaded(PageLoaded);
}
}
function PageLoaded(sender, args) {
//Do something
}
</script>

If you are using AJAX then the only way i have found yet to give an alert to a user on return to the Asynchronous post back is to add an “end request” handler to the PageRequestManager.
In this way you can tell the request manager to run a javascript function on returning from a Asynchronous post back event of AJAX.
Code for doing this is :
function load()
{
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
}
where “EndRequestHandler” will be the name of your javascript function you want to call.
Call the above function in Onload event of tag:
<body onload=”load()”>
function EndRequestHandler()
{
alert(“You record has been saved successfully”);
}
Now If you want to give a different message based on your logic in server side code (code behind) then you can use a server side Hidden Field:
<input id=”hdnValue” type=”hidden” runat=”server” value=”" />
Set its value in server side code on Asychronous Post Back:
Protected Sub btn_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCreateSample.Click
If condition Then
hdnValue.value = “do this”
Else
hdnValue.value = “do that”
End If
End Sub
Now you can check the value of this Hidden Field in your Client Side EndRequestHandler function and give a different alert to user based on its value:
function EndRequestHandler()
{
if (document.getElementById(‘<%= hdnValue.ClientID %>’).value == “do this”)
{
alert(“You record has been saved successfully”);
}
else
{
alert(“There is an error”);
}
}

you can use below code with if jquery is used
This is to show saved message and hide that message after 5 seconds after update panel is updated
function pageLoad() {
window.Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
}
function EndRequestHandler()
{
window.setTimeout(function () {
var label = window.$get('<%= lblMsg.ClientID%>');
if (label != null) { label.style.display = 'none'; }
}, 5000);
}

Related

How to disable button with Response Redirect

I Have two pages, Pages A and Pages B, in Pages A i have button which one will redirect to Pages B, then i try to back to Page A using button from browser.
Please your suggestion, how i can disable my button in Page A for not redirect again to Pages B.
OK. If you want to disable the browser's back button feature, then you can try the below JavaScript: Put it in the head tag of the Sign Up page
<script type="text/javascript">
function noBack() { window.history.forward() }
noBack();
window.onload = noBack;
window.onpageshow = function (evt) { if (evt.persisted) noBack() }
window.onunload = function () { void (0) }
</script>
Note: This will only block the feature of browser's back button but if you manually go back to the Sign Up page writing in the address bar, this then will not work.
One more thing, as you are using Session, you can integrate it with the JavaScript as follows:
<script type="text/javascript">
var someVar = "Hello";
//var someVar = <%=this.Session["UserId"]%>; //Keeping the session value in JavaScript variable
function noBack() {
if (someVar == "Hello") { //You can use - if (someVar != null)
window.history.forward()
}
}
noBack();
window.onload = noBack;
window.onpageshow = function (evt) { if (evt.persisted) noBack() }
window.onunload = function () { void (0) }
</script>

Show alert after postback

I have a button which calls stored procedure and binds gridview.
I found a code on stackoverflow for top alert bar like this:
function topBar(message) {
var alert = $('<div id="alert">' + message + '</div>');
$(document.body).append(alert);
var $alert = $('#alert');
if ($alert.length) {
var alerttimer = window.setTimeout(function () {
$alert.trigger('click');
}, 10000);
$alert.animate({ height: $alert.css('line-height') || '50px' }, 500).click(function () {
window.clearTimeout(alerttimer);
$alert.animate({ height: '0' }, 200);
});
}
}
Then in my button I try to call this function like this:
Dim script As String = String.Format("topBar({0});", Server.HtmlEncode("Successfully Inserted"))
Response.Write(script) 'Or even like this
ClientScript.RegisterStartupScript(Page.GetType(), "topBar", script, True)
But it simply does not work.
Can you guide me in right direction?
I always sort this type of problems with supplying a Boolean Property whether javascript should fire a piece of script or not. For example :
public bool IsDone { get; set; }
Sorry that the code is in C#
This is a property on code behind file. When I need to fire the javascript method, I simply make this true.
What I do on the aspx page is as follows :
<script>
if(<%= IsDone.ToString().ToLower() %>) {
alert("Done!");
}
</script>

How to avoid UpdatePanel scrolling on AutoPostBack?

I have an ASP.NET FormView within an updatepanel. I'm auto-saving the form by setting AutoPostBack=true for each of the items within the FormView.
This means the user can click a few elements in quick succession and fire off a few async postbacks almost simultaneously.
The issue I have is that the user is able to keep scrolling down the form while the async postbacks are not yet complete. The browser always scrolls back to the position it was in at the first postback.
Page.MaintainScrollPositionOnPostback is set to False.
I've tried all sorts of things in ajax and jquery with:
pageLoad
add_initializeRequest
add_endRequest
document.ready
etc..
but I always only seem to be able to access the scroll Y as it was on the first postback.
Is there any way to retrieve the current scroll Y when the postback completes, so I can stop the scrolling occurring? Or perhaps is it possible to disable the scrolling behaviour?
Thanks!
Update
Thanks to #chprpipr, I was able to get this to work. Here's my abbreviated solution:
var FormScrollerProto = function () {
var Me = this;
this.lastScrollPos = 0;
var myLogger;
this.Setup = function (logger) {
myLogger = logger;
// Bind a function to the window
$(window).bind("scroll", function () {
// Record the scroll position
Me.lastScrollPos = Me.GetScrollTop();
myLogger.Log("last: " + Me.lastScrollPos);
});
}
this.ScrollForm = function () {
// Apply the last scroll position
$(window).scrollTop(Me.lastScrollPos);
}
// Call this in pageRequestManager.EndRequest
this.EndRequestHandler = function (args) {
myLogger.Log(args.get_error());
if (args.get_error() == undefined) {
Me.ScrollForm();
}
}
this.GetScrollTop = function () {
return Me.FilterResults(
window.pageYOffset ? window.pageYOffset : 0,
document.documentElement ? document.documentElement.scrollTop : 0,
document.body ? document.body.scrollTop : 0
);
}
this.FilterResults = function (n_win, n_docel, n_body) {
var n_result = n_win ? n_win : 0;
if (n_docel && (!n_result || (n_result > n_docel)))
n_result = n_docel;
return n_body && (!n_result || (n_result > n_body)) ? n_body : n_result;
}
}
Main page:
...snip...
var logger;
var FormScroller;
// Hook up Application event handlers.
var app = Sys.Application;
// app.add_load(ApplicationLoad); - use pageLoad instead
app.add_init(ApplicationInit);
// app.add_disposing(ApplicationDisposing);
// app.add_unload(ApplicationUnload);
// Application event handlers for component developers.
function ApplicationInit(sender) {
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (!prm.get_isInAsyncPostBack()) {
prm.add_initializeRequest(InitializeRequest);
prm.add_beginRequest(BeginRequest);
prm.add_pageLoading(PageLoading);
prm.add_pageLoaded(PageLoaded);
prm.add_endRequest(EndRequest);
}
// Set up components
logger = new LoggerProto();
logger.Init(true);
logger.Log("APP:: Application init.");
FormScroller = new FormScrollerProto();
}
function InitializeRequest(sender, args) {
logger.Log("PRM:: Initializing async request.");
FormScroller.Setup(logger);
}
...snip...
function EndRequest(sender, args) {
logger.Log("PRM:: End of async request.");
maintainScroll(sender, args);
// Display any errors
processErrors(args);
}
...snip...
function maintainScroll(sender, args) {
logger.Log("maintain: " + winScrollTop);
FormScroller.EndRequestHandler(args);
}
I also tried calling the EndRequestHandler (had to remove the args.error check) to see if it reduced flicker when scrolling but it doesn't. It's worth noting that the perfect solution would be to stop the browser trying to scroll at all - right now there is a momentary jitter which would not be acceptable in apps with a large user base.
(The scroll top code is not mine - found it on the web.)
(Here's a helpful MSDN page for the clientside lifecycle: http://msdn.microsoft.com/en-us/library/bb386417.aspx)
Update 7 March:
I just found an extremely simple way to do this:
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(beginRequest);
function beginRequest()
{
prm._scrollPosition = null;
}
</script>
You could bind a function that logs the current scroll position and then reapplies it after each endRequest. It might go something like this:
// Wrap everything up for tidiness' sake
var FormHandlerProto = function() {
var Me = this;
this.lastScrollPos = 0;
this.SetupForm = function() {
// Bind a function to the form's scroll container
$("#ContainerId").bind("scroll", function() {
// Record the scroll position
Me.lastScrollPos = $(this).scrollTop();
});
}
this.ScrollForm = function() {
// Apply the last scroll position
$("#ContainerId").scrollTop(Me.lastScrollPos);
}
this.EndRequestHandler = function(sender, args) {
if (args.get_error() != undefined)
Me.ScrollForm();
}
}
}
var FormHandler = new FormHandlerProto();
FormHandler.Setup(); // This assumes your scroll container doesn't get updated on postback. If it does, you'll want to call it in the EndRequestHandler.
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(FormHandler.EndRequestHandler);
Simply put the Timer control within the content template.
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Timer ID="Timer1" runat="server" Interval="5000" OnTick="Timer1_Tick">
</asp:Timer>
<asp:ImageButton ID="ImageButton1" runat="server" Height="350" Width="700" />
</ContentTemplate>
</asp:UpdatePanel>

Assyncronous interaction using Sys WebForms PageRequestManager

I'm trying to display a panel to the user when an asynchronous call is made, but only if that happend from a specific call.
using the normal "get control" script I have mine like:
function pageLoad() {
try {
var manager = Sys.WebForms.PageRequestManager.getInstance();
manager.add_endRequest(OnEndRequest);
manager.add_beginRequest(OnBeginRequest);
}
catch (err) { }
}
function OnBeginRequest(sender, args) {
//alert('Start\n\n' + sender + '\n\n' + args);
var p = document.getElementById('ajaxLoadingPanel');
p.style.visibility = 'visible';
p.style.display = 'inline';
}
function OnEndRequest(sender, args) {
//alert('End\n\n' + sender + '\n\n' + args);
var p = document.getElementById('ajaxLoadingPanel');
p.style.visibility = 'hidden';
p.style.display = 'none';
}
but my question is How do I know the methods of sender and args?
I went through the MSDN and they talk nothing about the methods we can use, and there is no intellisence in VS2008 for this part...
any ideas? I want to get a list of methods and properties for both sender and args that I can use of this javascript API.
This documentation is helpful:
http://msdn.microsoft.com/en-us/library/bb398976.aspx
It has a table of all the events on PageRequestManager and what their event args are. Then the event args documents their properties, etc. The sender is always the PageRequestManager.
Debug in ScriptDebugger and find out the contents of sender and args
you can identify that which control has caused the postback
To know which element caused postback, you can use args.get_postBackElement().id.

Scroll to top of page after async post back

So I need to scroll to the top of the page after an async post back in an asp.net update panel.
The code I used was this:
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestEventHandler);
function EndRequestEventHandler(sender, args)
{
scrollTo(0,0);
}
However, I only want this to be run when I click on a certain button which causes the async postback.
How do I wire this event up in my code behind button event?
Any help would be appreacited, thanks!
My quest for a solution is finally over. This question was part of the help, and the rest I found here.
Had to override ASP.NET Ajax's behaviour of memorizing the scroll position:
<script type="text/javascript">
var manager = Sys.WebForms.PageRequestManager.getInstance();
manager.add_beginRequest(beginRequest);
function beginRequest()
{
manager._scrollPosition = null;
}
</script>
And then use the bit of code in the answer here, on the codebehind of the page I wanted to scroll to the top:
ScriptManager.RegisterStartupScript(this, typeof(MyControl), "someText", "window.scrollTo(0, 0)", true);
I used Farinha's answer (thanks!) and changed it slightly so I could just call the method any place I wanted to scroll to the top, but maintain the scroll position otherwise.
public static void ScrollToTop(int intPosY = 0)
{
string strScript = #"var manager = Sys.WebForms.PageRequestManager.getInstance();
manager.add_beginRequest(beginRequest);
function beginRequest()
{
manager._scrollPosition = null;
}
window.scroll(0," + intPosY.ToString() + ");";
Page pagCurrent = GetCurrentPage();
ScriptManager.RegisterStartupScript(pagCurrent, pagCurrent.GetType(), string.Empty, strScript, true);
return;
}
public static Page GetCurrentPage()
{
return (HttpContext.Current.Handler as Page);
}
Try this:
protected void myButon_Click(object sender, EventArgs e)
{
ScriptManager.RegisterStartupScript(this, typeof(MyControl), "someText", "alert('!');", true);
}
Improving on the answers of #Farinha and #Bradford Scott, the code can be simplified to this:
var script =
"Sys.WebForms.PageRequestManager.getInstance()._scrollPosition = null; " +
"window.scrollTo(0, 0);"
ScriptManager.RegisterStartupScript(this, GetType(), "key", script, true);
I'm actually not even sure why their scripts work since they add the reset of the Sys.WebForms.PageRequestManager's _scrollPosition as an add_beginRequest handler, and here we are actually returning from the request.
Anyway, resetting the _scrollPosition right before making your own scrollTo() call definitely works.

Resources