传递MVC模型数据到客户端打字稿code [英] Passing MVC Model Data to Client-side TypeScript Code

查看:118
本文介绍了传递MVC模型数据到客户端打字稿code的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用MVC,我有时服务器的模型数据传递到客户端JavaScript使用剃刀注入的JavaScript,如下:

When using MVC, I sometimes pass the server's model data to the client-side JavaScript by using Razor injected into the JavaScript, as follows:

<script type="text/javascript">
    var myClientGuid = '@Model.MyServerGuid';
</script>

这台名为 myClientGuid 到服务器端模型属性的值JavaScript变量 MyServerGuid 。当它到达客户端,code看起来像这样在浏览器中:

This sets a JavaScript variable named myClientGuid to the value of the server-side model property MyServerGuid. When it reaches the client, the code looks something like this inside the browser:

<script type="text/javascript">
    var myClientGuid = 'EF0077AB-0482-4D91-90A7-75285F01CA6F';
</script>

这允许外部JavaScript文件使用这个变量。

This allows external JavaScript files to use this variable.

我的问题是,在打字稿,因为的所有的code必须是通过外部文件中引用的,什么是要通过服务器端领域的打字稿code的最好方法?外部code文件不能包含剃刀code。我应该使用相同的技术方法同上,在视图中,在项目中混合JavaScript和打字稿?

My question is, in TypeScript, since all code must be referenced via external files, what is the best way to pass server-side fields to TypeScript code? External code files cannot contain Razor code. Should I use the same technique as above, in the View, mixing JavaScript and Typescript within the project?

推荐答案

打字稿编译器只需要知道你的服务器端领域的存在。要做到这一点,最简单的方法是使用环境声明(见规范第10条)。例如,如果你有一个需要使用myClientGuid一个.TS文件,你可以做

The TypeScript compiler just needs to know that your server-side fields exist. The easiest way to do that is to use ambient declarations (see section 10 of the spec). For example, if you had a .ts file that needed to use myClientGuid, you could do

declare var myClientGuid: string;

在主要.TS文件的顶部。编译器不会产生code这个VAR声明,这样你就不会破坏任何东西。现在,任何文件引用该.TS文件就会知道,有在全球范围内提供一个myClientGuid字符串。

at the top of your main .ts file. The compiler will not generate code for this var declaration, so you won't clobber anything. Now any files that reference that .ts file will know that there is a myClientGuid string available in global scope.

这篇关于传递MVC模型数据到客户端打字稿code的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆