1

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 scenario and it does trigger but the scroll keeps getting back to the top, whave have I done wrong here?

JavaScript:

$.ajax({
        type: "GET",
        url: "AdminListUsers.aspx?column=Disabled&direc=False&a=chstat&z=+",
        success: function loadDoc() {
            window.scrollTo(window.pageXOffset, window.pageYOffset);
        }
    });

C#:

var toggleUrl = "AdminListUsers.aspx?column=" + (IsClicked.FirstOrDefault().Key ?? "Name") + "&direc=" + (IsClicked.FirstOrDefault().Value) + "&a=chstat&q=" + id.ToString() + "&d=" + disabled + "&z=" + Server.UrlEncode(txtSearchFor.Text);

var hl = new HyperLink();
hl.Text = status;
hl.Style.Add(HtmlTextWriterStyle.Color, (disabled ? "red" : "green"));
hl.NavigateUrl = toggleUrl;
hl.Attributes.Add("onclick", "loadDoc();return true;");
cell.Controls.Add(hl);
tr.Cells.Add(cell);
  • Remove all the `xhttp` references and the `if` statement in the `success` handler. Just put the `window.scrollTo()` call in there. – Rory McCrossan Jun 14 '17 at 07:58
  • @RoryMcCrossan Look at the updated question. Is that what you meant? Because this does not work either. – andrekordasti Jun 14 '17 at 08:00
  • Yep, that's at least now syntactically correct. When you say it doesn't work, what does happen? – Rory McCrossan Jun 14 '17 at 08:10
  • @RoryMcCrossan I mean it does not scroll to the current position, it just scrolls back up again as if it were first time you refresh the page. All though: If I specifiy that I want it to scroll to the very bottom, it does, so it's so strange why the values of the scroll positions is undefined. – andrekordasti Jun 14 '17 at 08:15
  • there's an almost identical question here: https://stackoverflow.com/questions/44520790/page-rendering-with-asp-net-ajax – ADyson Jun 14 '17 at 09:03
  • The problem is because it's actually navigating to the link specified in the hyperlink, if ajax is to be used there's no need to have a navigateURL specified, and the default behaviour needs to be suppressed by the script. – ADyson Jun 14 '17 at 09:04
  • @ADyson I cannot remove the NavigatedURL, because the data wont be updated in that case. So how am I supposed to do that? Show me in code please what you mean. – andrekordasti Jun 14 '17 at 09:06

1 Answers1

1

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.

ADyson
  • 57,178
  • 14
  • 51
  • 63
  • I cannot access any of my variables in code-behind at $("#<%= myLink.ClientID %>"). How come? – andrekordasti Jun 14 '17 at 10:46
  • I don't know what this means? Why would you expect to access code-behind variables from javascript? What are you trying to do? – ADyson Jun 14 '17 at 10:47
  • Well I cannot resolve ´myLink´ in javascript, so what should I put in there? – andrekordasti Jun 14 '17 at 10:49
  • `<%= myLink.ClientID %>` should get the ID of the `h1` hyperlink as generated by ASP.NET. I assume this is happening in an `.aspx` or `.ascx` file? – ADyson Jun 14 '17 at 10:50
  • ´h1.ID = "myLink";´ you are saying h1 (the number one) instead of the letter l. Is these two different hyperlinks? And yes it's an .aspx file – andrekordasti Jun 14 '17 at 10:54
  • sorry hl, not h1. I misread it. But yes it should find that. Assuming you included my extra line `hl.ID = "myLink";` in your C# code? I have corrected the sample now to be `hl` instead of `h1`. – ADyson Jun 14 '17 at 11:04
  • Yes I fixed it, but the problem is still that "The name 'myLink' does not exist in the current context" and "Cannot resolve symbol myLink" at $("#<%= myLink.ClientID %>").click(function (event) – andrekordasti Jun 14 '17 at 11:07
  • This a compile error, not a runtime error, right? Sounds like something in your environment. See if this helps https://stackoverflow.com/questions/19027025/name-does-not-exist-in-the-current-context . You could also try just running it anyway, if it will let you. Sorry it's a long time since I worked with ASP.NET WebForms. MVC is so much easier ;-) – ADyson Jun 14 '17 at 11:09
  • What is the difference? I get "There were build errors. Would you like to continue and run the last sucessful build?" from VS dialog. Anyway the main problem is that my scroll position values are undefined, because the solution I created is working when I hardcode a value, for example $(selector).scrollTop(position) where position specifies the vertical scrollbar position in pixels, so I just need to save the current position in a session or something so that the application remembers before redirecting. – andrekordasti Jun 14 '17 at 11:18
  • this solution **is not redirecting**. That was whole point, yes? To avoid a redirect? If you want to redirect, then there is no sense in using ajax. – ADyson Jun 14 '17 at 11:23
  • That is true, but I still have no solution for this since your code wont compile. What should I do? – andrekordasti Jun 14 '17 at 11:24
  • Also I cannot use ID because the site crashes for some reason, it is a big application keep in mind. – andrekordasti Jun 14 '17 at 11:24
  • "the site crashes for some reason," is not an error message, or even a problem description. It's very difficult to help with such a vague statement. Not sure why the size of the application would have anything to do with the use of a control ID. – ADyson Jun 14 '17 at 11:29