Steven Sann
Steven Sann

Reputation: 578

how to use razor code in typescript instead of javascript

This is my .chstml code

@using MyProject.Constant.MyConstants

Inside .chstml , I use this constant value in javascript like

switch (value) {
    case @((int)MyConstants.ValueOne):

Now, I have to change this javascript to typescript file. I want to use those constant value in typescript.

How can I include the namespace MyProject.Constant.MyConstants inside typescript to use it?

Upvotes: 0

Views: 1623

Answers (1)

Tetsuya Yamamoto
Tetsuya Yamamoto

Reputation: 24957

Take note that you can't use server-side objects (including C# namespaces) directly inside external .ts files (with Razor syntax), such like external JS files. However, you can create hidden element in CSHTML file which has data- attribute to hold the integer value:

<div id="valueone" data-valueone="@MyConstants.ValueOne" style="display:none">...</div>

And convert it as constant integer value inside external .ts file with parseInt (suppose jQuery is used):

var valueOne = parseInt($('#valueone').data('valueone'));

Then put that value inside switch block as a case condition:

switch (value) {
    case valueOne:
        // do something
        break;

    // other cases

    default:
        // do something else
        break;
}

References:

TypeScript Converting a String to a number

TypeScript within .cshtml Razor Files

Pass value from c# to cshtml to TypeScript

Upvotes: 1

Related Questions