简体   繁体   中英

How to use inline C# in the browser instead of Javascript

I have just discovered Microsoft introduced Blazor which allows C# code to be run in the browser. When I looked at some tutorials it seems like you need asp.net core backend server for this to work. It'd be nice if I could type C# code in the browser like:

<script>

    //C# code
    string myName = "John";
    alert(myName);

</script>

instead of

<script>

    //Javascript code
    var myName = "John";
    alert(myName);

</script>

Can this be done?

No, you can't just put the C# code in a script tag. Browsers don't know how to parse and run C# code. What Blazor does is compile C# (on the server) into .Net assemblies, which are then run in the browser via WebAssembly . Details in the Blazor introduction . Here's an excerpt that seems relevant:

Blazor apps are based on components. A component in Blazor is an element of UI, such as a page, dialog, or data entry form.

...

The component class is usually written in the form of a Razor markup page with a .razor file extension. Components in Blazor are formally referred to as Razor components. Razor is a syntax for combining HTML markup with C# code designed for developer productivity. Razor allows you to switch between HTML markup and C# in the same file with IntelliSense support. Razor Pages and MVC also use Razor. Unlike Razor Pages and MVC, which are built around a request/response model, components are used specifically for client-side UI logic and composition.

The following Razor markup demonstrates a component ( Dialog.razor ), which can be nested within another component:

 <div> <h1>@Title</h1> @ChildContent <button @onclick="OnYes">Yes!</button> </div> @code { [Parameter] public string Title { get; set; } [Parameter] public RenderFragment ChildContent { get; set; } private void OnYes() { Console.WriteLine("Write to the console in C#! 'Yes' button was selected."); } }

And:

When a Blazor WebAssembly app is built and run in a browser:

  • C# code files and Razor files are compiled into .NET assemblies.
  • The assemblies and the .NET runtime are downloaded to the browser.
  • Blazor WebAssembly bootstraps the .NET runtime and configures the runtime to load the assemblies for the app. The Blazor WebAssembly runtime uses JavaScript interop to handle DOM manipulation and browser API calls.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM