maintain postback with WebForm_DoCallback - asp.net

Does anyone know how to maintain postback while calling WebForm_DoCallback? it always set the vertical scrollbar of the page to the very top.
thanks

I Call this method in onclick event of html input button, instead of asp:Button. Sample:
input id="ButtonCallServer" type="button" onclick="MyServerCall(txtSum.Value)"
function MyServerCall(args) { WebForm_DoCallback('__Page', args, ClientCallbackFunction, "", null, false); }

on the page you want to maintain position set the following page level directive:
<%# Page Language="..." MaintainScrollPositionOnPostback="true" ... %>
If you wanted you could set this for the whole site, in which case add the following to your web.config under the system.web block:
<pages maintainScrollPositionOnPostBack="true" />

i had similar problem yesterday after {don't remember what changes}.
the MaintainScrollPositionOnPostback just stopped working.
use this:
string postbackInvokerUniqueID = Request.Forms["__EVENTTARGET"];
if (!string.IsNullOrEmpty(postbackInvokerUniqueID))
Page.FindControl(postbackInvokerUniqueID).Focus();
that may not give the the exact scroll position, but is close enough

Related

How do I put a placeholder twice on master page?

I have a master page and I want to add a placeholder twice - so that I have the same placeholder in two places of the master page so that actual page just specifies content of the placeholder once and that content is rendered twice on the resulting page. The goal is to avoid duplication of content.
If I try to add a placeholder with the same id twice it won't compile - ASP.NET doesn't like that.
How do I achieve that? What are other options?
Place your placeholder in an Action, and call it where necessary.
<%
Action myPlaceholder = () =>
{%>
<asp:ContentPlaceHolder ID="X" runat="server" />
<%}
%>
...then call wherever necessary in code.
<% if (conditionMet)
myPlaceholder(); >%
The error occurs at compile time: a complaint will be made if placeholders with the same ID exist. This approach clears that hurdle, and gives a lot of flexibility.
I think you are probably looking for a user control:
http://msdn.microsoft.com/en-us/library/y6wb1a0e.aspx
With User Controls you can add your markup and code behind into an .ascx and then call this in your Master Page/Web Form multiple times, therefore avoiding duplicate code.
I haven't tried this, but you could lookup the contents of the placeholder you are interested in duplicating, and copying it in your code behind. This post: http://programcsharp.com/blog/archive/2009/01/22/test-if-masterpage-contentplaceholder-has-content-or-is-empty.aspx
has some good insight into manipulating master pages.

scroll go to the top page

net use web methods to save data from JavaScript when i press save the all page go the top how i can save state position after post back
You can set it programmatically
Page.MaintainScrollPositionOnPostBack = true;
In the page declaration
<%# Page MaintainScrollPositionOnPostback="true" %>
Or in the web.configs <system.web> section.
<pages maintainScrollPositionOnPostBack="true" />
The reason the page is returning to the top, is because it is being Submitted and hence reloaded.
If you want to keep the position of the page you have 2 options;
1) Use a Anchor (See: http://www.hypergurl.com/anchors.html)
2) Post your form using AJAX and then you do not need to reload the page
Option 2 is the prefered, if you are using webforms you could use an AJAX Update Panel, or if you are using MVC you can do it using JQuery.
try to setting the following page directive in your page
<%# Page MaintainScrollPositionOnPostback="true" %>
I solved the question, and my method of doing this was the following:
I put a javascript:void(0) in an a tag, as shown here:
<a href="javascript:void(0)">

hyperlink.NavigateUrl getting changed on master page (possibly by ResolveUrl() )

I have a hyperlink that in certain cases I want to change to show a jquery popup, but I'm having a strange problem when doing it on a master page. The following works in a regular page:
hyp1.NavigateUrl = "#notificationPopup";
Which renders as:
<a id="ctl00_hyp1" href="#notificationPopup">Example</a>
This is exactly what I want. The problem is with the exact same code on a hyperlink on the master page it renders as:
<a id="ctl00_hyp1" href="../MasterPages/#notificationPopup">Example</a>
It looks like it might be running the navigateUrl through ResolveClientUrl() or something when I'm setting it on the master page. I've tried swapping the <asp:hyperlink for a <a href runat=server, but the same thing happens.
Any ideas?
There is a note on MSDN Control.ResolveClientUrl method description.
The URL returned by this method is
relative to the folder containing the
source file in which the control is
instantiated. Controls that inherit
this property, such as UserControl and
MasterPage, will return a fully
qualified URL relative to the control.
So the behavior of master page in your exampe is fully predictable (although this is not a very comfortable to work with). So what are the alternatives?
The best one is to set the <a> as a client control (remove runat="server"); should work like a charm even in a master page:
Example
In the case if this control should be server side only: you could just build an URL from your code behind by using UriBuilder class:
UriBuilder newPath = new UriBuilder(Request.Url);
// this will add a #notificationPopup fragment to the current URL
newPath.Fragment = "notificationPopup";
hyp1.HRef = newPath.Uri.ToString();
Create a hidden field on your form and set the value to where you want to navigate / the url of the hyperlink instead of the hyperlinks navigate url. Then call the onclick method of the hyperlink in javascript and set the hyperlink there before the browser does the actual navigation.
<html><head><title></title></head>
<script type="text/javascript">
function navHyperlink(field)
{
field.href = document.getElementById('ctl00_hdnHypNav').value;
return true;
}
</script>
<input type="hidden" id="hdnHypNav" value="test2.html" runat="server"/>
<a href="" onclick="navHyperlink(this);" >click here</a>
</html>
Code behind would be:
hdnHypNav.value = "#notificationPopup";
You could also just try setting the url after the postback with below code, i.e. replace your code behind line with this one but I am not sure if it will work...
ScriptManager.RegisterStartupScript(this,this.GetType(),"SetHyp","$('ctl00_hyp1').href = '#notificationPopup';",True)
I found another way to solve the problem.
hyp1.Attributes.Add("href", "#notificationPopup");
Seeing as the whole reason I replaced my static hyperlink with a runat="server" one was to benefit from automatic resource-based localization, none of these answers served my needs.
My fix was to enclose the hyperlink in a literal:
<asp:Literal ID="lit1" runat="server" meta:resourcekey="lit1">
Example
</asp:Literal>
The downside is if you need to programmatically manipulate the link, it's a bit more annoying:
lit1.Text = String.Format("Example", HttpUtility.HtmlAttributeEncode(url));

How to scroll to bottom of page when postback finish in asp.net?

How to scroll to bottom of page when postback finish in asp.net?
I have many details in page when I click "Show Detail" in master detail, this page show many data in my page. So how to to scroll to bottom of page automatically?
from Hosam Kamel's page
To maintain the scroll position for the large web page you can use on of these methods :
1- use Web.config page section <pages maintainScrollPositionOnPostBack="true" />
: this will maintains the scroll positions for all the web site pages.
2- in the page declaration <%# Page MaintainScrollPositionOnPostback="true" %> : this will maintains the scroll position for this page only.
3- programmatically from code behind System.Web.UI.Page.MaintainScrollPositionOnPostBack = true; : this will maintains the scroll position for this page only (the same as page declration).
You could register the a javascript to move the scroll to the position of some control that you want, like this:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
RegisterStartupScript("ScrollScript", "document.getElementById('objectId').scrollIntoView(true);");
}
}
Changing the objectId in the script for the Id of the object you want to scroll to.
As noted by Guy Starbuk in the comments, RegisterStartupScript is deprecated in .Net 4 and now the recommended way to register a script is:
ClientScript.RegisterStartupScript(GetType(), "ScrollScript", "document.getElementById('objectId').scrollIntoVie‌​w(true)", true);
In asp.net web pages you can add an OnClientClick event to the control causing the server post back to scroll the page to the bottom.
<asp:Button ID="MyButton" runat="server" Text="Submit" OnClick="MyButton_Click" OnClientClick="window.scrollTo(0, document.body.scrollHeight);" />
Create an anchor on the page, then on onload:
window.location.href = "#myanchor"
One thing missing from the answers here is a delay. It's all well and good if there is no change in the height of the web page during load. But if there are a lot of images and your trying scroll past them; they can bump your view back up again.
What is needed is a window.onload function call:
ClientScript.RegisterStartupScript(GetType(), "ScrollScript", "window.onload = function() {document.getElementById('objectid').scrollIntoView(true);}", true);

asp:ImageButton not firing onclick event

I have a page that uses a master page, several RequiredFieldValidators, and the Web Toolkit autocomplete extender. The following code only shows the bare minimum of the page:
<%# Page Language="C#"
AutoEventWireup="true"
CodeFile="Login.aspx.cs"
MasterPageFile="~/master.master"
Inherits="Login" %>
<asp:Content id="Content1"
contentplaceholderid="ContentPlaceHolder1"
runat="server">
<asp:UpdatePanel ID="pnlUpdate" runat="server">
<ContentTemplate>
<div>
<asp:ImageButton class="submitButton"
imageurl="images/button_submit.gif"
id="btnSubmit"
runat="server"
onclick="btnSubmit_ServerClick"/>
</div>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
Code-behind:
protected void btnSubmit_ServerClick
(object sender, ImageClickEventArgs e)
{
//breakpoint here does not get hit
}
The <form runat="server"> tag is in the master page. The code above does not fire the onclick event. If I get rid of the master page and add a form tag to the page, it works. Is the form tag in the master page not supported, or is this supposed to work somehow?
alt text http://digitalcopy.warnerbros.com/images/mainmenu.gif?provider=00079&disc=03403AAA-1D20-47F2-91FA-5EE632832659
You can also check if your ImageButton does not trigger validation. If it does set its CausesValidation property to false (of course if it makes sense).
I had a similar issue (different scenario). I used Page.RegisterRequiresRaiseEvent(ImageButton) and my onclick event started to fire. Why I needed to do that? I don't know.
My solution was to set the ImageButton's CausesValidation to false.
I have a similar issue with the image button and found the root cause. You are using
"ib.ID = i + ":" + j;"
as the ID of the ImageButton, the ":" is illegal name to use, as you are creating it programmatically, ASP.NET allows it to be created.
At runtime, if you look at the HTML source of the page, you will see the special characters are either ignored or replaced with "_". So the page is unable to find the correct control, thus the event won't fire. Try changing the name with plain text, the event will fire.
ib.ID = i + ":" + j;
should be changed to
ib.ID = i.toString()+":"+j.toString();
If it still doesn't work try making use of the StringBuilder to buildup the ID and assign it later to ib.ID property
This is solution that worked for me
If you are binding through data bound controls then use OnCommand attr instead of OnClick attr
You have to have the control in a form runat=server somewhere, it can be in the Master page or the .aspx file. Double check that the master page form tag is runat=server
AutoEventWireup is the property that allows the syntax you are using. Double check the setting in the Master Page, WebForm and it can also be set in the web.config.
if that doesnt work, you can always explicilty code it (which I prefer)
<script runat=server>
protected override void OnInit(EventArgs e)
{
btnSubmit.Click += delegate(object sender, EventArgs e1)
{
};
base.OnInit(e);
}
</script>
UpdatePanel can mess with server side events being raised also, so try it without the UpdatePanel. And I am sure you have a ScriptManager in the Master Page
From the code you supplied, you seem to be missing the <asp:scriptmanager> from your page. You must do one of the following:
Have the <asp:scriptmanagerproxy> on the page and the <asp:scriptmanager> on the master page.
Have <asp:scriptmanager> on your page and no <asp:scriptmanager> on the master page.
Personally, I recommend having the <form> tag on the master page, but that's personal preference.
You can always try taking out the UpdatePanel and seeing if it works. I usually start without the UpdatePanel, get everything working the way I want and then add in the UpdatePanel and debug anything that causes.
The form in the MasterPage works for me so the ScriptManager/ScriptManagerProxy mentioned by #Keltex might be an issue, though I forget them sometimes and usually get away with it.
With the UpdatePanel the button's click event will be handled via Javascript, so you might grab FireBug or equivalent (depending on browser) and follow through what actually is happening. Is it tripping on the validation and you don't see it? Is there a JS error somewhere (the Control Toolkit isn't perfect always)? Is the page actually posting back at all and just not hitting the event handler?
On my webpage i am creating imagebuttons dynamically inside a table that is contained by an updatepanel. The buttons are created by this code:
for (int i = 0; i < 15; i++)
{
TableRow tr = new TableRow();
for (int j = 0; j < 20; j++)
{
TableCell tc = new TableCell();
ImageButton ib = new ImageButton();
ib.Click += new ImageClickEventHandler(ImageButton1_Click);
ib.ImageUrl = "../img/defaultCell.jpg";
ib.ID = i + ":" + j;
tc.Controls.Add(ib);
tc.Width = 25;
tc.Height = 25;
tr.Cells.Add(tc);
}
GameTable.Rows.Add(tr);
}
}
The image buttons will not trigger click events. HOWEVER, if the line 'ib.ID = ...' is commented out, they do! That single alternation seems to fix all the issues.
I have no idea why.
If anyone can explain this, and also tell me how to trigger events keeping the ability to set button id's, i'd be much thankful
I think it may have something to do with the fact your re-assigning the id's after creating & assigning the event handler?
Do you even need to assign the id's? - Surely this is done for you anyway? - True removing the 'ib.ID = i + ":" + j;'
Make sure you use OnClick rather than onClick
Your update panel could be messing with the postback. Try it without the UpdatePanel and see if that is the culprit.
I had the same problem that OnClick event of ImageButton was not firing. But the actual problem was, at form level, I had onSubmit="return false;"
I was facing the same issue, where I was dynamically creating an ImageButton and click of that event was not triggering. hence, i created the Image button in if (IsPostBack) . Now it is working fine. And even if the page gets refresh, the ImageButton will be retained.
I've just solved a similar issue where OutputCache was enabled. When changing from asp:ImageButton to asp:Button, the event is correctly fired. Probably asp:ImageButton has some bug with OutputCache.
After none of the above suggestions worked for me, I did one more try by calling the button creation in OnInit(). This fixed my issue and now the OnClick event is firing.

Resources