Using TypeScript with ASP.NET MVC 5

Here, we will learn about integrating TypeScript in ASP.NET MVC 5. TypeScript can be integrated into any existing ASP.NET application easily. TypeScript is one of the fastest-growing and highly adopted programming languages.

You can learn the basic introduction and how to setup typescript from my previous articles. Create a new ASP.NET MVC 5 application or take any existing application in which you have to integrate the TypeScript.

Roadmap for developing the application

  • Create the configuration file
  • Create a typescript file for writing the TypeScript code
  • Using TypeScript in ASP.NET application
  • Calling TypeScript method from HTML

Create the configuration file

Create a new tsconfig.json file also know as TypeScripr configuration file. We have to create it in the root folder.

using-typescript-with-asp-net-mvc-5-1

You have to create a file like this in the TsConfig folder or whatever folder name you have to give.

using-typescript-with-asp-net-mvc-5-2.png

Open the tsconfig.json file and write the following code in it.

{
  "compilerOptions": {
    "noImplicitAny": false,
    "noEmitOnError": true,
    "removeComments": false,
    "sourceMap": true,
    "target": "es5",    
    "outDir": "../appJS"
  },
  "exclude": [
    "node_modules",
    "wwwroot"
  ]
}

Whenever we use TypeScript with ASP.NET MVC 5 application or any other application we have to create a tsconfig.json file. It is used to tell the TS compiler what to do with TypeScript file like output directory, transpile it, etc.

Understanding the tsconfig.json file

  • outDir: It tells the TS compiler where to put the JS file generated by Transpile
  • target: module in form of es5 standard
  • sourceMap: these file help us to debug the TS code in the browser

Create a typescript file for writing the TypeScript code

Create an app.ts file in the folder where you have written the tsconfig.json file.

Write the following code in the app.ts file

function GreetUser(user: string) {
    return "<h2>Hello " + user + ", Lets learn TypeScript</h2>";
}

function ChangeText() {
    document.getElementById("msgDiv").innerHTML = GreetUser("Shaikh");
}

Using TypeScript in ASP.NET application

Once you build the application, the app.js file will automatically be added in the appJS folder and you can include that file in the application.

using-typescript-with-asp-net-mvc-5-3

Calling TypeScript method from HTML

Open the Index.cshtml file and write the following code in it.

@{
    ViewBag.Title = "Home Page";
}

<div class="row">
    <button class="btn btn-default" onclick="ChangeText()">Change Text</button>
    <h2 id="msgText"></h2>
</div>

@section scripts{
    <script src="~/appJS/app.js"></script>
}

Code in Action:

output

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories