1

My main goal is to call a C# method whenever the user scrolls to the bottom of my page. I searched for a solution using blazor alone, but couldn't find one.

Therefore, I'm using jQuery to register the scroll event and then I'm using JSInvokable to call the C# Method.

jQuery code:

<script>
    //Used to register scroll event.
    $(window).scroll(function () {
        if ($(window).scrollTop() + $(window).height() == $(document).height()) {
            DotNet.invokeMethodAsync('Blazor-Example', 'OnScroll');
        }
    });
</script>

.Net code (in the .razor page):

@code {
  //This is called from jquery
  [JSInvokable("OnScroll")]
  public static void OnScroll()
  {
    //TODO: How to get hold of the razor component instance?
  }
}

This works fine, but I want to call an instance method in my .razor page, not a static one.

In other words: How can I get the instance of the razor page from JavaScript?

I tried using a static instance of the type __generated__[Name_of_the_razor_page] that is set during OnInitialized(), but then my code just wouldn't compile with no errors shown.

If it is not possible to get the instance of a razor component, is there another way to register my scroll event?

1 Answer 1

6

You need to send a DotNetObjectReference to your javascript and use this reference to invoke your callback :

@inject IJSRuntime jsRuntime
...
@code {
  protected override void OnInitialized()
  {
     jsRuntime.InvokeVoidAsync("scroll.init", DotNetObjectReference.Create(this))
  }
  //This is called from jquery
  [JSInvokable("OnScroll")]
  public void OnScroll()
  {
    //TODO: How to get hold of the razor component instance?
  }
}
window.scroll = {
   init: dotnetHelper => {
      $(window).scroll(function () {
        if ($(window).scrollTop() + $(window).height() == $(document).height()) {
            dotnetHelper.invokeMethodAsync('OnScroll')
               .then(_ => { });
        }
    })     
   }
};
Sign up to request clarification or add additional context in comments.

1 Comment

Had to @inject IJSRuntime jsRuntime into the razor page and of course remove the static from my method. Works great, thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.