サンプル
* ラジオボタンに従い、サーバからデータをajaxで取得して、リストに反映
* リスト内を選択し、ボタンを送ればサーバ側で受け取ることができる
モデル
* SampleKnockoutModel.vb
Namespace Models
Public Class SampleKnockoutModel
Public Property CountryId As String
Public Property CompanyNames As List(Of ListItem)
Public Property CompanyIds 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.CompanyIds)"
data-bind="options: items, optionsText: 'Text', optionsValue: 'Value'"
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 companyId In Model.CompanyIds
@<p>Company ID : @companyId</p>@<br />
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 ListItem))
Public Sub New()
CompanyInfoDictinary = New Dictionary(Of String, List(Of ListItem)) From
{
{"JP", New List(Of ListItem) From
{
New ListItem() With {.Value = "J01", .Text = "Sony"},
New ListItem() With {.Value = "J02", .Text = "Hitachi"},
New ListItem() With {.Value = "J03", .Text = "Toshiba"},
New ListItem() With {.Value = "J04", .Text = "Fujitsu"}
}
},
{"US", New List(Of ListItem) From
{
New ListItem() With {.Value = "U01", .Text = "Google"},
New ListItem() With {.Value = "U02", .Text = "Yahoo"},
New ListItem() With {.Value = "U03", .Text = "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