Explain Codes LogoExplain Codes Logo

Using Razor within JavaScript

javascript
javascript-best-practices
razor-integration
javascript-organization
Alex KataevbyAlex Kataev·Mar 9, 2025
TLDR

To use Razor within JavaScript, use @ in .cshtml files:

// No magic, just data transmutation var data = @Html.Raw(Json.Serialize(Model.Data));

The above example converts the Razor values to a JSON object for use in JavaScript. This pattern efficiently bridges server-side models with client-side scripts.

Stay clean, stay organized: Best practices

When venturing into Razor-JavaScript integration, consider the following essential strategies:

Move JavaScript out of the way

Instead of spray-painting your code with scattered JavaScript script blocks, organize your JavaScript into functions to call from within your Razor view:

// The funnel of clarity function initialize(data) { // Using data parameter instead of Razor syntax // A clean JavaScript function, no Razor intruding }

Now pass the Razor-generated JSON to your JavaScript function:

<script> // Knock-knock. Who's there? // It's your fresh and clean data! initialize(@Html.Raw(Json.Serialize(Model.Data))); </script>

DOM data storage: The data-attribute strategy

When you need to tie data tightly to a DOM element, store your data directly within the HTML using data-attributes. Your JavaScript can access these attributes and absorb the data:

<!-- An HTML element tagged with juicy data --> <div id="user-info" data-user="@Html.Raw(Json.Serialize(Model.User))"></div>

Give static JavaScript a new home

Exile JavaScript unrelated to Razor variables to external .js files. This saves load time with caching and reduces the mess load times and file size:

// Total Eclipse of Razor - written and performed by .js file

To Ajax or not to Ajax

When data changes faster than a chameleon on a disco floor, AJAX is your choice. Fetching dynamic data keeps your JavaScript clean and separates server-side operations:

// Fetching the exclusive server-side stories $.getJSON("/api/userdata", function(data) { // Read, process, and enjoy the gossip });

Finer points when using Razor with JavaScript

Explore advanced techniques and get the most juice out of your Razor-JavaScript cocktail with the following tips:

Slim and trim with @: or text

Use @: or <text> tags when injecting JS code into the Razor file. This switches Razor into text mode, resulting in a leaner HTML output:

@if (someCondition) { // This isn't flab, this is potential energy! @: var conditionMet = true; }

C# helpers to the rescue

When tasks get repetitive, @helper methods come to the rescue. Put them in App_Code to keep it clean and favor reusability:

@helper EncodeForJs(MyModel model) { // Clone yourself, they said. It will be fun, they said. @Html.Raw(Json.Encode(model)) }

Iteration with a Razor flavour

Iterate through collections with Razor syntax for a familiar feel:

// Who let the C# out? Woof, woof, woof! var array = [ @foreach (var item in Model.Collection) { @: '@Html.Raw(item)', } ];

Razor: contained within script tags

Ensure Razor is always wrapped in <script> tags when working with JavaScript:

<script> @foreach (var item in Model.Collection) { <text> // Razor comes to JavaScript's party, brings its own drinks createItem('@Html.Raw(item.Name)', '@Html.Raw(item.Value)'); </text> } </script>