简体   繁体   English

从ASP.NET MVC视图调用TypeScript类方法

[英]Calling a TypeScript class method from a ASP.NET MVC view

I have a TypeScript class like the following 我有一个像下面的TypeScript类

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. 我需要在select元素onchange事件上呈现一个属性,以便它将调用TypeScript类方法。

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? 我的问题是如何找到确切的定义,以便能够正确调用TypeScript函数?

This is how the compiled js looks like... 这就是编译后的js的样子...

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

    function myFunc(rsw_id) {
       alert(rsw_id);
    }
});

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. 当对类等使用导出和导入时,生成的JavaScript代码取决于requireJS,您需要在项目中正确安装和配置它。
RequireJS is great but in some cases you just separate your classes to different files and not into different modules. RequireJS很棒,但是在某些情况下,您只是将类分为不同的文件而不是不同的模块。
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. 可以将RequireJS与ASP.NET MVC结合使用,并且有很多不错的文章,但是对我来说,这是一个过分的,复杂的代码,没有真正的麻烦。 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). 因此, 我从类中删除了所有导出/导入表达式,并选择了None作为模块系统设置 (在项目属性的TypeScript部分)。 Now the generated javascript exposes all the classes as functions that can be easily addressed. 现在,生成的javascript将所有类公开为可以轻松解决的函数。

This article really helped me: http://www.mobzystems.com/blog/creating-a-simple-typescript-web-app/ 这篇文章确实对我有帮助: http : //www.mobzystems.com/blog/creating-a-simple-typescript-web-app/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM