asp:linkbutton (navigating to specific page section on post back) - asp.net

I have some linkbuttons to update my gridview which is in the middle of the page. Everytime I hit edit or delete etc the window scrolls to the top on the page that gets posted back. I want it to stay focused on the grideview. I have tried a javascript function but for some reason it did not work.
(edit: the following works as far as scrolling is concerned but prevents postback)
here is what I tried
<script type="text/javascript" language="javascript">
function goto() {
window.scrollTo(10, 1100);
}
</script>
<asp:LinkButton ID="lbtnGo" runat="server" OnClientClick="javascript:goto();return false;">GO</asp:LinkButton>
source
How can I do this?

Did you try with <%# Page MaintainScrollPositionOnPostback="true" %> in the page declaration?
Regards

Client-side event fires before server-side. So even if you scroll window to correct position - after postback you will be returned to the top. You can add the following code to your server-side LinkButton click event handler:
if (!this.IsStartupScriptRegistered("ScrollToGrid"))
{
String scriptString = "<script language=\"JavaScript\">";
scriptString += "window.scrollTo(10, 1100);";
scriptString += "</script>";
this.RegisterStartupScript("ScrollToGrid", scriptString);
}
this will add javascript block to your page after postback

There are, depending on the .NET framework properties available that can help one out:
ASP.NET 1.x: use SmartNavigation. ASP.NET 2.0: use MaintainScrollPositionOnPostBack. Use an UpdatePanel control to asynchronously update parts of a page
and the best way for this is UpdatePanel control to asynchronously update parts of a page

Related

Access to events?

i have a question about generating images at runtime which are also links. Ok, so what i was going to do was create an ImageButton, and then set the onClick event to something such as:
window.open('http://www.themagicfinger.com/')
Which means it would look like:
newImage.Click += (window.open('http://www.themagicfinger.com/'));
But then i realised that this doesnt work, because it looks for a method which matches the event delagate.
So my question is, is this the best way to achieve what i want, and if so, how can i make it work?
Another option that came in my head would be to wrap the image in an tag, but i think this way its better.
Thanks
What you need is OnClientClick:
<asp:ImageButton id="ImageButton1" runat="server" OnClientClick="window.open('http://www.themagicfinger.com/'); return false;" ImageUrl="MyButton.png" />
This property is a string, not event, and you can also assign it from within the code behind:
ImageButton1.OnClientClick = "window.open('http://www.themagicfinger.com/'); return false;";
If you're asking how to use server-side code to tell the client to open a browser window, you can't. The server-side code has no means of telling the client to do that. The only thing you'd be able to do from server-side code is emit client-side that does this. And in that case, why use the server-side code at all?
Using jQuery for example, you can attach the click event like this:
<!-- page header (including loading jQuery), other stuff that's before the image, etc. -->
<img src="/path/to/image" alt="some text" id="imgOpenWindow" />
<!-- the rest of the page -->
<script type="text/javascript">
$(document).ready(function() {
$('#imgOpenWindow').click(function(){
window.open('http://www.themagicfinger.com/');
});
});
</script>
If for some reason you need to use an ImageButton control for this then it would look like this:
<!-- page header (including loading jQuery), other stuff that's before the image, etc. -->
<asp:ImageButton run="server" id="imgOpenWindow" ImageUrl="/path/to/image" AlternateText="some text" />
<!-- the rest of the page -->
<script type="text/javascript">
$(document).ready(function() {
$('#<%= imgOpenWindow.ClientID %>').click(function(){
window.open('http://www.themagicfinger.com/');
});
});
</script>
But I'm not sure what the behavior would be with the post-back. It might override the JavaScript handler (by posting back before your handler is executed) or post-back after the window opens, etc. I would consider that behavior to be undefined and unreliable. An Image control will do the trick, though, if you don't need the button post-back capabilities.

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.NET invoke ASP.NET buttons server event in javascript

I am having an ASP.NET page with one Asp.net button control and a normal html link (anchor tage) I want to invoke the postbackl event of asp.net button control when someone clicks on the link.
I used the below code
<a href="javascript:myFunction();" class="checkout" ></a>
<asp:Button ID="btnCheckout" runat="server" Visible="false"
onclick="btnCheckout_Click" />
and in my javascript i have
function myFunction()
{
var strname;
strname = "Test";
__doPostBack('btnCheckout','OnClick');
}
But when runnin gthis , i am getting an error like __doPostBack is undefined
Can any one tell me why it is ?
Thanks in advance
This anyway wouldn't have worked. When you make your .NET control invisible by using 'Visible="false"' it isn't rendered, that means not available at the client.
Back to your question.
1- Where is myFunction defined? Between the tag?
2- Are there more .NET controls on the page? If there aren't any other .NET controls, .NET doesn't add all the scripts that are required for postbacks and stuff.
Why not do the following (based on TheVillageIdiot answer):
<asp:LinkButton ID="lbtnCheckout" runat="server" CausesValidation="false" OnClick="lbtnCheckout_Click" CssClass="checkout" />
With the above example you don't need the fake button and make it invisble. You still can do your postback. Way more cleaner approach I would say.
First of all I tried your code and also not get anything like __doPostBack, then I added another button on the page which was visible but it was all the same. Then I added a LinkButton and got __doPostBack method. You can do post back from javascript but then EventValidation is problem, as it does not allow this kind of thing. I had to use the following to overcome it and it worked:
protected override void Render(HtmlTextWriter writer)
{
ClientScript.RegisterForEventValidation(
new PostBackOptions(btnCheckout, "OnClick"));
base.Render(writer);
}
I think I'm bit incoherent in answering so I'll mark it as wiki :)

Form tag on ASP.net page

I have a web application that has a page that loads the content from the database. I want to be able to put a form in the dynamic content, but .net doesn't let the inside form perform it's action. Is there a way to allow this or some other way I can get a form on a dynamic content page?
--EDIT--
I think I need to clarify something. This is an aspx page that loads content from the database. As far as I know, the text I pull from the db and stick in the Label is never compiled or processed by the .net wp, thus I can't use the code behind to fix this issue.
This is a common problem, when you want to have a non-postback form to a 3rd party site (like a PayPal button, for example).
The problem occurs because HTML doesn't let you have form within a form, and most ASP.NET pages have a <form runat="server" /> "high up" in the HTML (or in the Master page).
My favorite solution is to hide the "high up" form tag, while still showing all of the content. Then you can feel free to dump any tags you want in the body. If you do this dynamically you can choose on a page-by-page basis which pages have custom forms.
I created a class called GhostForm.cs to handle this. You can read all about it here:
http://jerschneid.blogspot.com/2007/03/hide-form-tag-but-leave-content.html
There can only be one form on the page (the asp form); you have to use that form somehow.
To clarify, there can only be one form processed.
Not with webforms, no. You have to work within the one, full page form by using an event handler connected to a Button to LinkButton. Fortunately, it's pretty easy to do:
foo.aspx:
...
<asp:TextBox id="txtFoo" runat="server" />
<asp:Button id="btnFoo" runat="server" onclick="btnFoo_Click />
...
foo.aspx.cs:
...
protected void btnFoo_Click(object sender, EventArgs e)
{
string s = txtFoo.Text;
// do something with s
}
...
Dino Esposito has an article from MSDN magazine that covers handling multiple forms or "simulating" sub forms in ASP.Net that might just answer all your questions.
http://msdn.microsoft.com/en-us/magazine/cc164151.aspx
Any work around would be hacky and very ugly. By design asp.net uses a form tag to post and get data. This is why they call it a Web Forms Application. Html does not allow nested forms. What you want to do is use a WebRequest in your code behind.
If you are trying something like a paypal button you could simply use something like this.
Markup:
<div id="PayPalButtonContainer" runat="server"></div>
Code Behind:
public static string GetPayPalButtonMarkup()
{
const string markup = #"https://www.paypal.com/cgi-bin/webscr
?cmd=_xclick&business={0}
&item_name=Widget
&amount={1}
&currency_code=USD";
return markup;
}
PayPalButtonContainer.InnerHtml = string.format(GetPayPalButtonMarkup,"YOUR PAYPAL USER NAME", "YOUR PRICE VALUE");
you either have to deal with the postback by adding a server side click event handler to what you want to be the "sub forms" submit button (this is how web formas deals with multiple submit type buutons on the same page) or do soemthing clever with AJAX if you dont want a full post back
I've run across this issue before. One workaround that I have done is to place my code that I want my action to be done upon inside of an asp:Panel. With the panel you can set the attribute of "DefaultButton" to a button inside of the panel, and clicking the button (or pressing "enter") will fire that button's click event. I've found this quite handy when wanting to submit a "form" by pressing enter when I have a master page that contains the only allowable asp:Form.
Hope this helps.
When I first came across this problem, I found the simplest solution for me was to simple COPY and PASTE the Master page and give it a slightly different name, something like:
SiteNameMasterPage 'Default page with FORM tag
SiteNameMasterPageNF 'No Form tag
And then depending on wether I wanted a FORM tag or or not, simply change the masterpage link at the top of my CONTENT-PAGES, like this
<%# Page Title="" Language="VB" MasterPageFile="~/SiteName.master" %>
<%# MasterType VirtualPath="~/SiteName.master" %>
<!-- This masterpage has the default FORM tag -->
or
<%# Page Title="" Language="VB" MasterPageFile="~/SiteNameNF.master" %>
<%# MasterType VirtualPath="~/SiteNameNF.master" %>
<!-- This masterpage does NOT have the default FORM tag -->
and then in the content page, wherever I want to place my form I can include the <form> tag

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