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?

2
  • 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. Commented Dec 27, 2018 at 5:36
  • @TetsuyaYamamoto, yes, .ts is in a separate file. Commented Dec 27, 2018 at 5:37

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.