ASP.NET Core 2: Passing Values from Razor to TypeScript scripts

Often in a Razor page in ASP.NET Core we’ll need to pass some value to a Typescript script to have it do something meaningful. Here’s a simple way. (I’m assuming your Typescript file is automatically compiled to JavaScript)

Let’s say we have a mythical ConfigEngine script that does stuff, but needs to know on what ID to do the stuff to.

Step 1: Create a TypeScript file defining the script:

var ConfigEngine = ConfigEngine || (function() {
    var _configId = 0;
    return {
        init: function(configId) { 
           _configId = configId;
        doStuff: function() {
            alert("Did stuff");

Step 2: In your Razor page initialize the script and send it a value from the server:

<script src="~/js/ConfigEngine.js"></script>

Leave a Reply

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

You are commenting using your 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