S&box Wiki
Home
/
Edit A Razor Overview
View
Edit
History
No Category
Developer Overview
The Project System
Publishing To Asset Party
Getting Started With Hammer
Mapping Basics
Mapping Entities
Advanced Mapping Techniques
Getting Started with Modeldoc
Animgraph & Animation
Physics
Modeldoc Nodes
Advanced Modelling
UI Basics
Styles & Stylesheets
Razor Templates
Game Menus
Materials
Built In Shaders
Shaders
Shader Reference
Sounds & Audio
Particles
Getting Started
Making Games
Input
Networking
Physics
Rendering
Editor & Tools
VR
Misc
Playing Guides
Console Commands & Variables
Dedicated Server
Log in to edit
A Razor Overview
<cat>UI.Razor</cat> <title>A Razor Overview</title> # What are Razor components? Asp.net has this thing called [Razor](https://en.wikipedia.org/wiki/ASP.NET_Razor). Filename is `FriendName.razor` ``` @using Sandbox; @using Sandbox.UI; @namespace Menu <root class="friend-name @FriendClasses()">@Friend.Name</root> @code { public Friend Friend { get; set; } string FriendClasses() { if (Friend.IsMe) return "is-me"; if (Friend.IsFriend) return "is-friend"; return ""; } } ``` As you can see, it's html with c# mixed in. This code creates a new panel class called `FriendName`, which just shows a friend's name. # Switching between code and html If you start something with @, it'll be c#. This is easier to understand in visual studio because you'll get intellisense around it. <upload src="1/8dab7803c799870.png" size="26827" name="image.png" /> You'll switch back to html as soon as you do a html element, or close the curly braces. # Changing State The UI will be rebuilt when we think the state has changed (interactions usually). If you change the state and need to force the UI to rebuild, you can call `StateHasChanged()`. This won't rebuild the page instantly, it'll just invalidate so it'll be rebuilt on the next frame - you don't have to worry about calling it multiple times. # Loops Where `Categories` is a list of categories. ``` @foreach ( var category in Categories ) { var c = category.category == CurrentCategory ? "active" : ""; <button @onclick=@( () => ChangeCategory( category.category )) class=@c icon="@category.icon">@category.title</button> } ``` # Panels If an html element starts with a capital letter then we assume it's a panel and will try to create/use that class directly. This gives your code a rigidity - because if that panel type changes, your old code will need to too. You can also set properties on the class directly with attributes. If your attribute starts with a capital letter it will be assumed to be a member of the panel. Here's `LobbyChatEntry` ``` @using Sandbox; @using Sandbox.UI; @namespace Menu.Lobby <root class="card"> <div class="card-image" style="background: url( avatar:@Entry.Friend.Id )"> </div> <div class="card-body"> <row> <FriendName Friend=@Entry.Friend></FriendName> <div class="time">@Entry.Created.ToShortTimeString()</div> </row> <h3>@Entry.Message</h3> </div> </root> @code { public Lobby.ChatEntry Entry { get; set; } } ``` and here's a snippet of `LobbyChat` ``` @foreach (var entry in Lobby.ChatEntries ) { <LobbyChatEntry Entry=@entry></LobbyChatEntry> } ``` You can see how we use LobbyChatEntry directly, and set Entry directly. # Root element If your element starts with a <root> element, it'll represent the root of the panel. ``` // Warning.razor <root class="warning"> </root> ``` The above will end up with a single panel of type `Warning` with the class of `warning`. ``` // Warning.razor <div class="warning"> </div> ``` The above will end up with a panel of type `Warning`, with a child `Panel` with the class `warning` # Events You can hook regular panel events with attributes starting with `@on`. Here are some examples. ``` <button @onclick=@SaveChanges>Save Changes</button> <button @onclick=@( () => Log.Info( "Clicked!" ) )>Save Changes</button> <button @onclick=@( ( PanelEvent e ) => Log.Info( $"Clicked {e.This}!" ) )>Save Changes</button> ``` # Callbacks If you're creating a Panel type and it has an event, you can set that action like any other panel attribute. ``` <Switch value=@Value ValueChanged=@( ( bool b ) => Log.Info( $"Switched to {b}" ) )></Switch> ``` # @ref You can get a reference to a created panel using @ref. References are only available after the UI has been built (because the UI elements won't exist before then). After the ui is built `OnAfterTreeRender` is called - which you can override to access the references. ``` <div @ref=ThePanel>This is my panel</div> @code { public Panel ThePanel { get; set; } } ``` It should be noted that the reference may change when the UI gets re-built due to changes. If you're accessing panels via ref then this is something you should be thinking about and handling. For example, in the code below `ThePanel` will be null until showPanel is true and it is rebuilt. If you set showPanel to false again, `ThePanel` will become null again after a rebuild. ``` @if ( showPanel ) { <div @ref=ThePanel>This is my panel</div> } @code { public Panel ThePanel { get; set; } public bool showPanel; } ``` # Early Return You can return early in your component if you don't want to render it for some reason.. ``` @if ( Player == null ) { <div>This player isn't valid</div> return; } <div>All about @Player.Name<div> ``` # @code The `@code` block allows you to add code which isn't part of the UI. Here you can override any member that you would usually be able to override on Panel. <warning> While the Embedded `@code` tag does have some limitations: - Visual studio code analysis and code cleanup do not run. - C# Codegen is not run on .razor embedded code right now </warning> The created `Panel` class is declared as `partial`, so you can also add "code behind" by creating a .cs file with a partial class if you choose. There are some special Razor specific methods that you can override, which will make things a bit easier. ## OnParametersSetAsync OnParametersSet This is called when any of the Parameters change. This allows you an opportunity to reinitialize any other data. The Async version is useful if you have to query some other data source based on external input. ## virtual void OnAfterTreeRender( bool firstTime ) Called after the UI has been built. At this point all the child panels have been created, so if you have created anything with `@ref` that you need to initialize in some other way, this is the best place for that. ## int BuildHash() We need to know when to rebuild the UI. We only want to do it when the state has changed - because it would be a huge waste of time to do it any other time. By default the UI is updated after any event (mouse over, click etc) or when a parameter changes. If you want to kind of watch some external variables and update when they change, you can use the BuildHash function for that. ``` <div>@DateTime.Now</div> @code{ protected override int BuildHash() { return HashCode.Combine( DateTime.Now.ToString() ); } } ``` In the example above, we're showing the UI in the component so want to update it every time it changes. We do this by providing the hash of the string we're using in the hash. ``` @code{ protected override int BuildHash() { return HashCode.Combine(LobbyFrontPage.IsInLobby, Global.InGame); } } ``` In the example above we rebuild the UI whenever the player's lobby and ingame status changes. # <style> You can embed styles in your component. The styles will only apply to your component (and its children). ``` @using Sandbox; @using Sandbox.UI; @namespace Menu.CurrentGame <style> .card { padding: 8px; } .card-image { width: 50px; height: 50px; border-radius: 100px; margin-right: 10px; } .friend-name { font-size: 23px; } </style> <root class="card"> <div class="card-image" style="background-image: url( avatar:@Member.Id )"> </div> <div class="card-body"> <FriendName Friend=@Member Override=@Name></FriendName> </div> </root> @code { public string Name { get; set; } public Friend Member { get; set; } } ``` # Stylesheets You can include stylesheets with `@attribute` ``` @using Sandbox; @using Sandbox.UI; @attribute [StyleSheet( "/UI/Styles.scss" )] ``` Note that when splitting up your C#, Razor and CSS code into different files, you will want to follow the following format: `Example.razor`, `Example.razor.cs`, `Example.razor.scss`. This will fold all files into one in Visual Studio as well as ensure that live updates to your CSS are recognised. Also, if you name everything the same, you can just write `@attribute [StyleSheet]`. # Two Way Binds Sometimes you want to bind a variable to a control, and if it changes it, sync the value back. That's what two way binds are. You create a two way bind using `:bind` after the attribute name. ``` <SliderEntry min="0" max="100" step="1" Value:bind=@IntValue></SliderEntry> @code { public int IntValue{ get; set; } = 32; } ``` In the example above, the value is initially set to 32. If the value changes in the Slider, then it sets our IntValue to that value. If our value changes, it sets the Slider value.
S&box Wiki
Development
Developer Overview
6
Editor Overview
General FAQ
System Requirements
The s&box wiki
Troubleshooting
Useful Links
The Project System
4
Adding Assets
Creating a Game Project
Project Settings Window - Games
Project Types
Publishing To Asset Party
2
Uploading assets
Uploading projects
Hammer
Getting Started With Hammer
3
Getting Started With Hammer
Making Your First Map
Mapping Resources
Mapping Basics
7
Cordons
Hotspot Materials
Selection Sets
Standard Mapping Dimensions
Tool Materials
Tools Visualisation Modes
Using Entities That Require a Mesh
Mapping Entities
2
Creating a Door
Light Entities
Advanced Mapping Techniques
8
Collaborating With Prefabs and Git
Instances
Prefabs
Quixel Bridge Plugin
Tilesets
Tilesets-Advanced
Tilesets-Proxies
VIS Optimizations
Models & Animation
Getting Started with Modeldoc
7
Automatic Model Setup
Breakpieces
Creating a Model
Guide to Models
Importing Rust Weapons
LODs
ModelDoc FAQ & best practices
Animgraph & Animation
4
Animations without Animgraph
AnimEvents, AnimGraph Tags, Attachments
Animgraph
Delta Animations
Physics
3
Cloth Physics
Collisions, Physics & Surface Types
Jiggle Bones
Modeldoc Nodes
1
Custom ModelDoc nodes
Advanced Modelling
6
Bodygroups
Citizen
First Person
IKChains and Stride Retargeting
Morphs
Vertex Normals
User Interface
UI Basics
6
Custom Fonts
Embedding Websites
Enabling Pointer Events
Events and Input
UI Basics
UI with Components
Styles & Stylesheets
1
Video Backgrounds
Razor Templates
4
A Razor Overview
Aliases and SetProperty Attributes
Generic Components
Templates
Game Menus
1
Making a Custom Pause Screen
Materials & Shaders
Materials
5
Guide to Materials
Material Attributes
Material Resources
Texture Settings
Using Dynamic Expressions
Built In Shaders
2
Foliage Shader
Glass Shader
Shaders
4
Compute Shaders
Constant Buffers
Material API
Shading Model
Shader Reference
5
Anatomy of Shader Files
Getting rid of Tex2D macros
Shader Reference
Shader States
Texture Format Cheat-Sheet
Other Assets
Sounds & Audio
4
Guide to Sounds
Sound Events
Sound Occlusion
Soundscapes
Particles
5
Creating animated sprites
Creating your first particle effect
Understanding Particle Editor
Using custom sprites
Using particle systems from C#
Coding
Getting Started
5
Cheat Sheet
Learning Resources
Setting up Rider
Setting up Visual Studio
Setting up Visual Studio Code
Making Games
2
Components
GameObjects
Input
4
Commands
ConVars
Input System
Speech Recognition
Networking
7
Auth Tokens
Http Requests
Lobby System
Networked Types
Networking Basics
RPCs
WebSockets
Physics
5
Collisions
Hitboxes
Joints
Traces
Triggers
Rendering
3
Render Tags
RenderHooks
Scenes
Editor & Tools
5
Guide to Widgets
Hammer API
Hammer Gizmos
Hotload Performance
Widget Docking
VR
3
Getting Started
VR Input
VR Overlays
Misc
10
Asset Types
Attributes and Component Properties
Backend API
Code Accesslist
CPU Performance Profiling
DisplayInfo
package/find
Setting Up A Navigation Mesh
Threaded Tasks
TypeLibrary
Playing
Playing Guides
3
Default Keybinds
Proton
s&box on macOS (Experimental)
Console Commands & Variables
1
Launch Arguments
Dedicated Server
1
Dedicated Servers