はじめに
* ASP.NET MVC で変更検知(ダーティ・チェック)を実装してみる
* 無駄な通信を極力避けるため、サーバ側でのチェックを行わず、
クライアント側(JavaScript)のみで実装する
* 「簡易版」「knockout.js利用版」「hiddenを使った版」を作ってみた
=> できれば、「knockout.js利用版」が一番スマートかと。
■簡易版
* 変更したら、問答無用に変わったと判断。
ビュー:Index.vbhtml
@ModelType WebAppli.Models.EmployeeListModel
@Code
ViewData("Title") = "Index"
Dim index As Integer = 0
End Code
@Using (Html.BeginForm("SendResult", "SampleMvc", FormMethod.Post, New With {.Id = "formID"}))
@<table>
<thead>
<tr>
<th>Delete?</th>
<th>ID</th>
<th>Name</th>
</tr>
</thead>
<tbody>
@For index = 0 To Model.Employees.Count - 1 Step 1
@<tr>
<td>@Html.CheckBoxFor(Function(model) model.Employees(index).IsChecked)</td>
<td>@Html.TextBoxFor(Function(model) model.Employees(index).EmployeeId)</td>
<td>@Html.TextBoxFor(Function(model) model.Employees(index).EmployeeName)</td>
</tr>
Next
</tbody>
</table>
@<input type="submit" value="Send" />
@<a href="http://www.yahoo.co.jp/" onclick="return checkToChangeValues()">Go yahoo!</a>
End Using
<script type="text/javascript">
var hasChanged = false;
$('#formID input').change(function () {
hasChanged = true;
});
function checkToChangeValues() {
if (hasChanged === true) {
return confirm(
'You have some changes.\nAre you sure you want to go to the other pages?');
}
return true;
};
</script>