Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where does code inside of @code runs in blazor server-side?

This might be a silly question. But I was trying to read more about Blazor, but I am always confused about @code. As I understand when you use @code inside of client-side blazor, everything runs locally on the client browser. So I have few questions:

  1. When you use blazor server-side, does the code inside of @code block runs on the server or still client?
  2. Does code inside of @code block is essentially converted to JS in blazor?
  3. Is it possible to run C# code locally on client in server-side blazor app? One case where I need it: an application where users edit document collaboratively together online(like google docs). I want to detect changes on server and tell every client that uses that doc to accept new changes.
like image 924
Mykhailo Bykhovtsev Avatar asked Jan 26 '26 16:01

Mykhailo Bykhovtsev


1 Answers

The @code block is used in both Blazor Server App and Blazor WebAssembly App to separate between the view (mixed C# + Html markup) part of a component and its code part. Both these parts are compiled into a single ComponentBase class.

When you use blazor server-side, does the code inside of @code block runs on the server or still client?

Your Blazor Server App runs on the server only. It emits Html diffs that are passed to the client browser over SignalR connection, and a Client SignalR code ( JavaScript) update the DOM element with the Html diffs passed to it.

Note that each interaction with the client-side (browser) of the Blazor Server App is executed on the server. Thus if you click on a button, the event handler attached to the click event of the button is executed on the server.

Does code inside of @code block is essentially converted to JS in blazor?

No. It is code in C# and remains so. If your app is in Blazor Server App, it is, once again, executed on the server. If it's in Blazor WebAssembly App, it is executed on the browser, in C#, .Net assemblies. It is not even compiled to wasm. It's .Net on the browser. However, the mono runtime which executes these .Net assemblies, is compiled to WebAssembly.

Is it possible to run C# code locally on client in server-side blazor app?

From what I've written above it is clearly evident that this is not the case. Again, Blazor Server App is executed on the server. Your use case is not an issue and can be solved easily...

Hope this helps...

like image 166
enet Avatar answered Jan 29 '26 12:01

enet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!