An @code expression is the component-side Razor construct for defining the properties and methods that support a Razor component’s markup. It replaces the page model class and serves as the counterpart to a Razor Page’s @functions expression. section 33.3.2
Use the @code section to:
- Expose data such as a People property for rendering. section 33.3.2
- Receive services through properties decorated with [Inject], rather than through a constructor. section 33.3.2
- Provide properties consumed by bindings, such as SelectedCity for a bound select element. section 33.3.2
Component backing code
A PeopleList component can define a People property and an injected DataContext directly in its Razor file, then consume both from the markup. section 33.3.2
Listing 33.7 The contents of the PeopleList.razor file in the Blazor folder
<table class="table table-sm table-bordered table-striped">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Dept</th>
<th>Location</th>
</tr>
</thead>
<tbody>
@foreach (Person p in People ?? Enumerable.Empty<Person>()) {
<tr class="@GetClass(p?.Location?.City)">
<td>@p?.PersonId</td>
<td>@p?.Surname, @p?.Firstname</td>
<td>@p?.Department?.Name</td>
<td>@p?.Location?.City, @p?.Location?.State</td>
</tr>
}
</tbody>
</table>
<div class="form-group">
<label for="city">City</label>
<select name="city" class="form-control" @bind="SelectedCity">
<option disabled selected value="">Select City</option>
@foreach (string city in Cities ?? Enumerable.Empty<string>()) {
<option value="@city" selected="@(city == SelectedCity)">
@city
</option>
}
</select>
</div>
@code {
[Inject]
public DataContext? Context { get; set; }
public IEnumerable<Person>? People =>
Context?.People.Include(p => p.Department)
.Include(p => p.Location);
public IEnumerable<string>? Cities =>
Context?.Locations.Select(l => l.City);
public string SelectedCity { get; set; } = string.Empty;
public string GetClass(string? city) =>
SelectedCity == city ? "bg-info text-white" : "";
}
Inspect a complete PeopleList.razor component combining markup, iteration, data access, injection, and binding. section 33.3.2
