Quantcast
Channel: プログラム の個人的なメモ
Viewing all articles
Browse latest Browse all 860

【ASP.NET MVC】ASP.NET MVC で、 knockout.js を使う ~入門編~

$
0
0

前提

 * 以下のJavascriptが必要。
  + knockout.-x.x.x.js
  => なかったら、以下の環境設定を行う

 ※ knockout.jsについて、以下の関連記事を参照のこと。
http://blogs.yahoo.co.jp/dk521123/35664953.html

準備:環境設定

http://blogs.yahoo.co.jp/dk521123/35596847.html
で行ったNuGetでインストールする

[1] Visual Studio で [ツール]-[NuGetパッケージ マネージャー]-[パッケージ マネージャー コンソール]を選択
[2] 以下のコマンドを入力する

Install-Package knockoutjs
https://www.nuget.org/packages/knockoutjs/

サンプル1

http://blog.shibayan.jp/entry/20111208/1323354859
を参考にサンプル(VB.NET)を作成してみた

ビュー

* Index.vbhtml
@Code
    ViewData("Title") = "Index"
End Code

<h2>Index</h2>

<ul data-bind="foreach: items">
    <li>名前: <span data-bind="text: name"></span>, 年齢: <span data-bind="text: age"></span></li>
</ul>

<script src="@Url.Content("~/Scripts/jquery-1.10.2.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/knockout-3.4.0.js")" type="text/javascript"></script>

<script type="text/javascript">
    $(function () {
        $.ajax({
            type: 'GET',
            url: '@Url.Action("GetJson")', // アクセス先のURL
        })
        .done(function (returnData) {
            var viewModel = {
                items: ko.observableArray(returnData)
            };
            ko.applyBindings(viewModel);
        });
    });
</script>

コントローラ

* SampleKnockoutController.vb
Imports System.Web.Mvc

Namespace Controllers
    Public Class SampleKnockoutController
        Inherits Controller

        Function Index() As ActionResult
            Return View()
        End Function

        Function GetJson() As ActionResult
            Dim jsonData = New List(Of Object) From
                {
                    New With {.name = "Mike", .age = 28},
                    New With {.name = "Tom", .age = 36},
                    New With {.name = "Smith", .age = 17}
                }
            Return Json(jsonData, JsonRequestBehavior.AllowGet)
        End Function
    End Class
End Namespace

出力結果

•名前: Mike, 年齢: 28
•名前: Tom, 年齢: 36
•名前: Smith, 年齢: 17

サンプル2

 * ラジオボタンに従い、サーバからデータをajaxで取得して、リストに反映
 * リスト内を選択し、ボタンを送ればサーバ側で受け取ることができる

モデル

* SampleKnockoutModel.vb
Namespace Models
    Public Class SampleKnockoutModel
        Public Property CountryId As String
        Public Property CompanyNames As List(Of String)
    End Class
End Namespace

ビュー

* Index.vbhtml
ModelType WebAppli.Models.SampleKnockoutModel

@Code
    ViewData("Title") = "Index"
End Code

<h2>Index</h2><br />
@Using (Html.BeginForm("SendResult", "SampleKnockout", FormMethod.Post))
    @Html.RadioButtonFor(Function(model) model.CountryId, "JP")
    @Html.Label("Japan")@<br />
    @Html.RadioButtonFor(Function(model) model.CountryId, "US")
    @Html.Label("USA")@<br />
    @<select multiple = "multiple" name="@Html.NameFor(Function(model) model.CompanyNames)"
             data-bind="options: items"
             size="7" width="200"></Select>
    @<input type="submit" value="Send" />
End Using

<script src="@Url.Content("~/Scripts/jquery-1.10.2.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/knockout-3.4.0.debug.js")" type="text/javascript"></script>
<script type="text/javascript">
    function ViewModel() {
        var self = this;
        self.items = ko.observableArray();
    }

    var viewModel = new ViewModel();
    ko.applyBindings(viewModel);

    $('input[name="CountryId"]:radio').change(function () {
        $.ajax({
            type: 'GET',
            url: '@Url.Action("GetList")', // アクセス先のURL
            data: {
                id: $(this).val(),
            },
        })
       .done(function (returnData) {
           viewModel.items(returnData.results);
       });
    });
</script>
* SendResult.vbhtml
@ModelType WebAppli.Models.SampleKnockoutModel

@Code
    ViewData("Title") = "SendResult"
End Code

<h2>SendResult</h2>

<p>ID : @Model.CountryId </p>

@For Each companyName In Model.CompanyNames
    @<p>companyName : @companyName</p>
Next

コントローラ

* SampleKnockoutController.vb
Imports System.Web.Mvc
Imports WebAppli.Models

Namespace Controllers
    Public Class SampleKnockoutController
        Inherits Controller

        Private CompanyInfoDictinary As Dictionary(Of String, List(Of String))

        Public Sub New()
            CompanyInfoDictinary = New Dictionary(Of String, List(Of String)) From
            {
            {"JP", New List(Of String)(New String() {"Sony", "Hitachi", "Toshiba", "Fujitsu"})},
            {"US", New List(Of String)(New String() {"Google", "Yahoo", "Microsoft"})}
            }
        End Sub

        Function Index() As ActionResult
            Return View()
        End Function

        Function GetList(ByVal id As String) As ActionResult
            Dim sendingValues = CompanyInfoDictinary(id)
            Return Json(New With {
                        .results = sendingValues},
                        JsonRequestBehavior.AllowGet)
        End Function

        Function SendResult(ByVal model As SampleKnockoutModel) As ActionResult
            Return View(model)
        End Function

    End Class
End Namespace


関連記事

knockout.js ~入門編~

http://blogs.yahoo.co.jp/dk521123/35664953.html

Viewing all articles
Browse latest Browse all 860

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>