Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing MVC Model Data to Client-side TypeScript Code

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?

like image 481
ChessWhiz Avatar asked Oct 09 '12 18:10

ChessWhiz


2 Answers

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>
like image 146
Geir Sagberg Avatar answered Nov 14 '22 01:11

Geir Sagberg


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.

like image 24
Brian Terlson Avatar answered Nov 14 '22 02:11

Brian Terlson