LoginSignup
3
5

More than 5 years have passed since last update.

TypeScriptをASP.NET MVCに組み込む

Posted at

今回はASP.NET MVCにTypeScriptを組み込んでみます。
環境はVisual Studio 2015です。

ASP.NET MVC サンプル作成

まず、ファイル->新規作成->プロジェクトでプロジェクト作成画面を開きます。
そして、ASP.NET Web アプリケーションを選択します。

create_new_asp_dotnet_sample.png

今回はEmpty、MVCを選択します。

empty_mvc.png

空のMVCなため構成はこんな感じです。

empty_mvc_constitution.PNG

空でなんもないんでControllers配下にHomeController.csを追加します。

HomeController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace TypeScriptSample.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }
    }
}

対応するViewをViews/Home配下に追加しましょう。

Index.html

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title></title>
</head>
<body>
    <label>Sample page</label>
</body>
</html>

これでソリューションを実行すれば下記画面が表示されるはずです。

empty_mvc_index.png

TypeScriptを組み込む

先ほど作成したサンプルにTypeScriptを組み込んでみましょう。
まず、ソリューションを右クリックし、追加->新しいフォルダでTypeScriptを置くフォルダを作りましょう。
フォルダ名は何でもいいです。

追加したフォルダを右クリックし、追加->TypeScriptファイルでTypeScriptファイルを作成します。

app.ts

class Person {
    private name: string;
    public getName(): string {
        return this.name;
    }
    constructor(name: string) {
        this.name = name;
    }
}

window.onload = function () {
    const p = new Person("Hoge");
    alert(p.getName());
}

ソリューションをビルドするとjsにトランスパイルされます。

mvc_with_ts_constitution.PNG

画面にapp.jsへの参照を追加しましょう。

Index.html

<!DOCTYPE html>

<html>
<head>        
    <script src="~/ts/app.js"></script>
    <meta name="viewport" content="width=device-width" />
    <title></title>
</head>
<body>
    <label>Sample page</label>
</body>
</html>

準備は整いました。

ソリューションを実行すると下記画面が表示されるはずです。

mvc_with_ts_index.PNG

以上、TypeScriptをASP.NET MVCに組み込むの回でしたー

3
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5