How to do client-side UI events in Blazor

asp.net-core blazor c#

Question

I just started playing around with Blazor and I can already see the great potential of this new framework.

I'm wondering, though, how it will handle doing simple things like setting focus on an input control? For instance, after I handle a click event, I want to set the focus to a text input control. Do I have to use JQuery for something like that, or will Blazor have some built-in methods for that sort of thing?

Thanks

Update: This is how I am doing this for now, until I learn more about Blazor. (This works, but I know there will be better ways of handling things like this when Blazor is ready for prime time.)

On my view I have the following Script section:

<script>
Blazor.registerFunction('FocusControl', (ctrl) => {
    document.getElementById(ctrl).focus();
    return true;
});
</script>

Then, in the Functions section I have this function:

private void FocusControl(string ctrl)
{
    RegisteredFunction.Invoke<bool>("FocusControl", ctrl);
}

Then I call it from a Refresh method. (This is using the sample code provided by TalkingDotNet at http://www.talkingdotnet.com/create-a-crud-app-using-blazor-and-asp-net-core/)

private async Task Refresh()
{
    todos = await Http.GetJsonAsync<ToDoList[]>("/api/ToDo");
    FocusControl("todoName");
    StateHasChanged();
}

Accepted Answer

Blazor is just the replacement (to be more precise "value addition") to the javascript. It is a client side only solution (but may be with some easy binding to ASP.Net in the future).

Still its completely based on html, and CSS. C# is replacing the js part using web assembly. So nothing has changed on how you access / modify html controls.

As of now (version 0.1.0) you have to rely on HTML DOM focus() Method to do what you intent to do (yes you have to use javascript as of now :( ).

// Not tested code
// This is JavaScript. 
// Put this inside the index.html. Just below <script type="blazor-boot"></script>
<script>
    Blazor.registerFunction('Focus', (controlId) => {
      return document.getElementById(controlId).focus();
    });
</script>

//and then wrap it for calls from .NET:    
// This is C#

public static object Focus(string controlId)
{
    return RegisteredFunction.Invoke<object>("Focus", controlId);
    //object type is used since Invoke does not have a overload for void methods. Don't know why. 
    //this will return undifined according to js specs
}

for more information you can refer below.

If you want to improve the pakaging of js neatly. you can do something like this. https://stackoverflow.com/a/49521216/476609

public class BlazorExtensionScripts : Microsoft.AspNetCore.Blazor.Components.BlazorComponent
{

    protected override void BuildRenderTree(Microsoft.AspNetCore.Blazor.RenderTree.RenderTreeBuilder builder)
    {
        builder.OpenElement(0, "script");
        builder.AddContent(1, "Blazor.registerFunction('Focus', (controlId) => { document.getElementById(controlId).focus(); });");
        builder.CloseElement();
    }

    public static void Focus(string controlId)
    {
         RegisteredFunction.Invoke<object>("Focus", controlId);
    }
}

then add this component to the root. (App.cshtml)

<BlazorExtensionScripts></BlazorExtensionScripts>
<Router AppAssembly=typeof(Program).Assembly />

Popular Answer

You can't directly call JavaScript function. You are required to first register your functions like,

<script>
 Blazor.registerFunction('ShowControl', (item) => {       
     var txtInput = document.getElementById("txtValue");         
     txtInput.style.display = "";
     txtInput.value = item;
     txtInput.focus();          
});
return true;
</script>

Then you need to declare a method in C# which calls this JavaScript function. Like,

private void CallJavaScript()
{
   RegisteredFunction.Invoke<bool>("ShowControl", itemName);
}

You can call this C# method on click of button. Like,

<button id="btnShow" class="btn btn-primary" @onclick(CallJavaScript)>Show</button>

This post Create a CRUD App using Blazor and ASP.NET Core shows a working demo of calling JavaScript from Blazor.




Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why