locked
Invoke Javascript Func in Blazor Server RRS feed

  • Question

  • User2041008840 posted

    Hello,
    I want to invoke this bootstrap select library into my blazor project but its not working. 
    I add library into _host.cshtml after the body tag 

    (https://developer.snapappointments.com/bootstrap-select)
    <script src="~/lib/bootstrap-select/bootstrap-select.min.js"></script>
    

    site.js

    windows.controls = () => {
     
        $(document).ready(function () {
            $('.selectpicker').selectpicker();
        });
    };

    After i also add invoke method into page.razor

     
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if(!firstRender)
       await IJSRuntime.InvokeAsync<object>("controls");
    }
    <select  class="form-control selectpicker">
                           <option value="0">--select--</option>
                           
                       </select>

     is their any wrong in my code ?

    Monday, March 30, 2020 5:03 AM

All replies

  • User475983607 posted

    Have you read the official "Call JavaSCript functions from .NET Core Blazor" reference documentation?

    Monday, March 30, 2020 11:41 AM
  • User2041008840 posted

    Yes. 
    When I applied into my project its not working. 


    Monday, March 30, 2020 2:37 PM
  • User-1330468790 posted

    Hi Prathamesh shende,

     

    If you are confident that all of the resources are loaded correctly, then what  you have to do is to correct two errors in your code which you could correct by referring to the link given by @mgebhard.

    • Change IJSRuntime to JSRuntime. The compiler should warn you the mistake about using JSRuntime.InvokeAsync<object>() with only one parameter.
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        if(!firstRender)
       await JSRuntime.InvokeAsync<object>("controls");
    }
    • Modify the site.js by changing windows to window. If you enter in the debug console, you will find that the error message displays 'Could not find 'controls' in 'window'
    window.controls = () => {
     
        $(document).ready(function () {
            $('.selectpicker').selectpicker();
        });
    };

      

    Note that here I am not sure about the logic in your project but if you use condition 'if(!firstRender)' in the method ' OnAfterRenderAsync', you can not invoke the js function.

    I think you should use 'if(firstRender)' which means the function will be called after each time the component has been rendered

    Make sure that you understand the lifecycle of the blazor pages so that you can easier achieve the target as you expected.

    https://docs.microsoft.com/en-us/aspnet/core/blazor/lifecycle?view=aspnetcore-3.1#after-component-render

     

    Hope this can help you.

    Best regards,

    Sean

    Tuesday, March 31, 2020 6:50 AM