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>
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>
This allows external JavaScript files to use this variable.
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?
Another solution (to avoid global variables) is to wrap the TypeScript code in a function that takes the needed server-side fields as parameters:
In TypeScript file:
function setupMyPage(myGuid:string) {
...
}
In .cshtml:
<script src='@Url.Content("<path-to-typescript>")'></script>
<script>
setupMyPage('@Model.MyServerGuid');
</script>
If you are using RequireJS, you can also export the setupMyPage
function as a module, to avoid adding the function to global namespace:
In TypeScript file:
export = setupMyPage;
In .cshtml:
<script>
require(['@Url.Content("<path-to-typescript>")'], function(setupMyPage) {
setupMyPage('@Model.MyServerGuid');
};
</script>
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With