0

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?

Tolga Evcimen
  • 7,112
  • 11
  • 58
  • 91
Steven Sann
  • 478
  • 1
  • 7
  • 27
  • You can use `data-` attribute in an element (e.g. `data-valueOne`) as replacement of direct usage with `$('#elementId').data('valueOne')` in TS side, but I want to know if you have separate .ts file to run the code. – Tetsuya Yamamoto Dec 27 '18 at 05:36
  • @TetsuyaYamamoto, yes, `.ts` is in a separate file. – Steven Sann Dec 27 '18 at 05:37

1 Answers1

1

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

Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61