Rendering output using Razor

When rendering output from a razor template it is important to remember the distinction between

@{ ...}  and @(...)

Curly braces will cause the output to execute, whilst the regular parenthesis will cause the output to render.

As an example that tripped me up during rendering of a ViewComponent in the CamperFinder demo, the following executes the output, but does not render it.

<div>     
@foreach (var vehicle in Model.Vehicles) {
  @await Component.InvokeAsync("VehicleSummary", vehicle);
}
</div>@

The inner await block is executed within the scope of the loop, within {} braces.

By adding parentheses around the await following renders the content as we want it.

<div>     
@foreach (var vehicle in Model.Vehicles) {
  @(await Component.InvokeAsync("VehicleSummary", vehicle));
}
</div>

Kudos: https://stackoverflow.com/a/44835742/75594

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

A WordPress.com Website.

Up ↑

%d bloggers like this: