As the title states, I wrote an ajax function that should scroll to the position the user were before getting redirected.
I wrote an alert
for test scen
The problem is because it's actually navigating to the link specified in the hyperlink. Then it's also trying to do the ajax request as well.
If ajax is to be used there's no need to have a navigateURL specified, and the default behaviour of the hyperlink needs to be suppressed by the script. Otherwise you'll get a full page refresh and a jQuery ajax request simultaneously. Since you've got jQuery installed you can do this most easily like this:
C#:
var hl = new HyperLink();
hl.Text = status;
hl.ID = "myLink";
hl.Style.Add(HtmlTextWriterStyle.Color, (disabled ? "red" : "green"));
hl.NavigateUrl = "#";
cell.Controls.Add(hl);
tr.Cells.Add(cell);
JS (using unobtrusive event handling):
$(document).ready(function() {
$("#<%= myLink.ClientID %>").click(function(event) {
event.preventDefault(); //stop the normal behaviour of the link
$.ajax({
type: "GET",
url: "AdminListUsers.aspx?column=Disabled&direc=False&a=chstat&z=+",
success: function() {
window.scrollTo(window.pageXOffset, window.pageYOffset);
}
});
});
});
This will stop the link from causing the whole page to be redirected, and just allow the content to be loaded via ajax.
N.B. If you are creating multiple instances of the hyperlink in a table, you would need to use classes rather than IDs to allow jQuery to locate it.
However, I would question what "AdminListUsers.aspx?column=Disabled&direc=False&a=chstat&z=+" actually returns. ormally an aspx page returns a whole HTML page including the <html>
, <body>
tags etc - if you put this inside another element such as a <div>
, it makes your page invalid - you cannot nest <html>
tags. If you want to use ajax, you should use a WebMethod (or other type of webservice) to return only the HTML that should actually be inserted into the element.