Render a product attribute safely in a Znode 9 Razor view
Select the value in the view model, handle absence, and let Razor encode untrusted text. Verify the data appears after the declared publication path.
In this guide
Keep lookup out of markup
Map the intended published attribute into a small view model before the view renders. The view should not query a database or infer a locale. This makes a missing product value an ordinary presentation state.
_ProductFinish.cshtml cshtml
@model ProductFinishViewModel
@if (Model != null && !string.IsNullOrWhiteSpace(Model.SurfaceFinish))
{
<dl class="product-specification">
<dt>Surface finish</dt>
<dd>@Model.SurfaceFinish</dd>
</dl>
}
@* Razor HTML-encodes Model.SurfaceFinish by default. *@
Define the view model
Keep the partial independent of the full product DTO. Map the intended attribute into this small model in your theme adapter, using the current product and locale. Make the class available to Razor through the view namespace imports or a fully qualified model name.
ProductFinishViewModel.cs csharp
public sealed class ProductFinishViewModel
{
public string SurfaceFinish { get; set; }
}
Preserve encoding and localization
Do not use raw HTML for an attribute value unless a separate sanitization contract exists. Treat the field label and the value as independently localizable. If the value is an option code, display the resolved localized label, not the stored key.
Test the empty and hostile cases
Check a product with a normal value, no value, an untranslated value, and a value containing angle brackets. The last case must render as text. Also verify that a saved value reaches the storefront only after the target version's required publication or cache operation.
References and further reading
Bring your next engineering question.
Need help with a safe storefront extension?
Independent guidance from GCG. Znode is a trademark of its owner. Examples use fictional data and are not official platform documentation. Suggest a correction.