2

I have a TypeScript class like the following

export class A
{
     myFunc(n : number){
         alert(n);
     }
}

I need to render an attribute on my select element onchange event so it will call the TypeScript class method.

writer.AddAttribute(HtmlTextWriterAttribute.Onchange,
           string.Format("javascript:new A().myFunc({0})", this.Number));

My question is how can I find the exact definition so I will be able to render a proper call to the TypeScript function?

This is how the compiled js looks like...

define("app", ["require", "exports", "jquery"], function (require, exports, $) {
   "use strict";
    Object.defineProperty(exports, "__esModule", { value: true });

    function myFunc(rsw_id) {
       alert(rsw_id);
    }
});
Yaron
  • 2,209
  • 3
  • 18
  • 33
  • I'm afraid it's not possible to use pure Typescipt in the `.cshtml`. See [this](https://stackoverflow.com/a/12695485/5126411) – Roman Koliada Nov 27 '17 at 13:57
  • @RomanKoliada sure it's not possible to use TS syntax, but a class declared in TS will be new-able and callable in cshtml provided the right JS is included – Titian Cernicova-Dragomir Nov 27 '17 at 14:12
  • 1
    TypeScript is rendered into a javascript... I'm on the search for the right js call as @TitianCernicova-Dragomir said... – Yaron Nov 27 '17 at 14:19
  • @Yaron, but if you include the JS in cshtml the syntax you use should work. Unless the class is in a namespace, in which case you should use new NamespaceName.A().myFunc({0}) – Titian Cernicova-Dragomir Nov 27 '17 at 14:26
  • Doesn't really work. see the latest edit of the post – Yaron Nov 27 '17 at 14:32
  • 1
    What king of tool are you using to compile your TS ? And seems that your tsconfig is configured to use require.js – OrcusZ Nov 27 '17 at 14:47
  • 1
    I guess you need to load a module first. See [this](https://stackoverflow.com/a/10816983/5126411) or [this](https://www.slightedgecoder.com/2017/05/22/setting-es6-environment-asp-net-mvc-5/) – Roman Koliada Nov 27 '17 at 14:51

1 Answers1

0

I hope it will help someone.
When using export and import for classes etc. the generated JavaScript code is dependent upon requireJS and you need to properly install it in your project and configure it.
RequireJS is great but in some cases you just separate your classes to different files and not into different modules.
Combining RequireJS with ASP.NET MVC is possible and there are great articles out there but for me it was an overkill and complicated the code without real neccassity. In my application there is only one module.
So, I removed all the export/import expressions from the classes and selected None for module system setting (At the project properties, TypeScript section). Now the generated javascript exposes all the classes as functions that can be easily addressed.

This article really helped me: http://www.mobzystems.com/blog/creating-a-simple-typescript-web-app/

Yaron
  • 2,209
  • 3
  • 18
  • 33