.NET Tips and Tricks

Blog archive

A Blazor Tip You Should Almost Certainly Ignore

In another column, I describe how you can, from JavaScript, call methods on C# objects defined in Blazor pages. As that sentence implies, however, there's no way to access properties on those objects ... at least, no official, documented way.

It can be done, however. To make a method on a class accessible from JavaScript, you decorate the method with the JSInvokable attribute. You can, it turns out, do the same thing with properties, like this:

public string FirstName { [JSInvokable] get; [JSInvokable] set; }

Once you've done that, you can read and set the FirstName property from a JavaScript function by treating the property's getter and setter like methods. This JavaScript code, for example, sets the FirstName property to "Jan" and then reads the value back out of the property (see that earlier column for all the ugly details):

cust.invokeMethod("set_FirstName", "Jan");
var fullName = cust.invokeMethod("get_FirstName");

While I've an auto-implemented property here, this also works with "fully implemented properties" with explicit getters and setters.

The Blazor documentation doesn't mention this "feature," which may mean that it's just a "happy accident" (it certainly seems to depend on the internal implementation of properties). As such it may be wiped out in the next release of Blazor or replaced with some better, slicker syntax.

But if you're working with Blazor and really want to access properties, there it is.

Posted by Peter Vogel on 10/10/2018


comments powered by Disqus

Featured

  • Building Secure and Scalable APIs in .NET 8

    Tony Champion: "From giving you access to the entire lifecycle of a request, the ability to configure and extend authentication and authorization, .NET 8 gives you the power to create APIs to meet even the most demanding needs."

  • What's New for Java Tooling in VS Code, Azure Cloud

    Java on Visual Studio Code gets a new tool to its extension pack, while Java on Azure upgraded the Azure Toolkit for IntelliJ and more in new regular updates for both properties.

  • Microsoft Highlights Third-Party Open-Source '.NET Smart Components'

    Microsoft has long acknowledged third-party vendor contributions to dev tooling ecosystems like Blazor and is now doing the same for its newly open-sourced .NET Smart Components.

  • Data Science Pack for VS Code Bundles Python, Data and Copilot Tools

    New extension pack bundles wildly popular tools for Python development, assisted by the AI-powered GitHub Copilot and a data wrangler.

Subscribe on YouTube