Skip to content

JavascriptConvert

Static Class

JavascriptConvert is a static utility class that serializes C# objects into JavaScript Object Literals instead of JSON strings. This is useful when embedding server-side state directly into <script> blocks, where a JavaScript object literal (without quoted property names) is more natural than a JSON string.

TechGems.StaticComponents
public static IHtmlContent SerializeObject(
object value,
bool useSingleQuotesOnStringValues = false
)

Serializes any CLR object into a JavaScript Object Literal. Property names are camelCased automatically (using Newtonsoft.Json’s CamelCasePropertyNamesContractResolver) and are not quoted, making the output valid JavaScript rather than JSON.

ParameterTypeDefaultDescription
valueobjectThe object to serialize.
useSingleQuotesOnStringValuesboolfalseWhen true, string values use single quotes (') instead of double quotes ("). Useful when the output is placed inside an HTML attribute.

Returns: IHtmlContent — the serialized object literal, safe for use in Razor views.

public class ChartComponent : StaticComponent
{
public ChartOptions Options { get; set; } = new();
}
public class ChartOptions
{
public string Title { get; set; } = "Sales";
public int MaxValue { get; set; } = 100;
public bool ShowLegend { get; set; } = true;
}
@using TechGems.StaticComponents;
@model ChartComponent
<div id="chart"></div>
<script static-script>
var options = @JavascriptConvert.SerializeObject(Model.Options);
initChart(options);
</script>

Output:

<script>
var options = {title: "Sales", maxValue: 100, showLegend: true};
initChart(options);
</script>

When embedding the object inside an HTML attribute (common with AlpineJS x-data), use single quotes to avoid breaking the attribute syntax:

<div x-data="@JavascriptConvert.SerializeObject(Model.Options, useSingleQuotesOnStringValues: true)">
...
</div>

Output:

<div x-data="{title: 'Sales', maxValue: 100, showLegend: true}">
...
</div>
FeatureJSONJavaScript Object Literal
Property names"quoted"unquoted
Directly assignable in JSNo (needs JSON.parse())Yes
Valid in x-data attributesAwkward (double-quote conflicts)Clean with single-quote mode