5

For obvious reasons we want to start with TS instead of JS in our project.

The problem we occurred are the variables who are set in the MVC Views which are set by the Model of the given View.

E.g. tes.cshtml:

@model Testmodel
<script>
  var test = {};
  var test.myProp = @Model.Testproperty;
<script>

Now in my test.ts I got an error when I try to get the test-variable because my TypeScript file doesn't know it.

Do I have a architecture miss-conception here? Or is there a trick to do that?

To be honest we have around 100 variables set and / or created in RazorViews, most likely a lot of Ressource-Variables from our resx files we would need e.g. in a java-script alert!

0

2 Answers 2

1

You can create definitions file and put all your global declarations there. For example:

declare interface SampleInterface{
    myProp:string;
    myFunc(someParameter:string):void;
}
declare var test:SampleInterface;
declare var someFunc: () => number;

More info on writing declaration files here.

Sign up to request clarification or add additional context in comments.

1 Comment

Can u expand this example for a function? With variables it seems to work well, thank you :)
1

One way is to attach to Window all your variables or even all your resource variables and after that you can create something like a helper in typescript where you can parse Window.Variables and Window.ResxVariables for your need.

Server-side you will need two dictionaries Variables and ResxVariables which can be statics in your base controller.

Then you will need two methods that will facilitate adding variables to these dictionaries

Variables.Add("Timezone", "GMT+2");

And

ResxVariables.Add("ExitAlert", "Please stay more");

These two methods will be accessible in your controller actions and you will have the possibility to add model properties too.

Then you will need a HtmlHelper that will help you render those dictionaries as objects attached to Window.

You will need to also support clearing those dictionaries when you render a new page or depends on your need.

When i used something like this, we had two dictionaries GlobalVariables and PageVariables. Global wasn't cleared when we render a new page, but PageVariables was.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.