サンプル
* トグル(Toggle) で開閉したタイミングで、サーバ(コントローラ)側とAjaxで接続するサンプル
/Controllers/DemoAjaxController.vb
Imports System.Web.Mvc
Namespace Controllers
Public Class DemoAjaxController
Inherits Controller
' GET: DemoAjax
Function Index() As ActionResult
Return View()
End Function
' GET: DemoAjax
Public Function ConnectByAjax(model As DemoAjaxModel) As ActionResult
' Threading.Thread.Sleep(2000) ' わざと遅延しテスト
Return Json(New With {Key .isSuccess = True, .result = model.IsClose},
JsonRequestBehavior.AllowGet)
End Function
End Class
End Namespace
/Models/DemoAjaxModel.vb
Public Class DemoAjaxModel
Private Property _IsClose As Boolean
Public Property IsClose As Boolean
Get
Return Me._IsClose
End Get
Set(ByVal value As Boolean)
Me._IsClose = value
End Set
End Property
End Class
/Views/DemoAjax/Index.vbhtml
二度押し防止 + 二度通信防止
<html>
<head>
<meta charset="UTF-8">
<link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/jquery-1.10.2.js")" type="text/javascript"></script>
<script type="text/javascript">
var jqXhr = null;
var allowAjax = true;
var DemoAjaxModel = {
isClose: false,
};
$(function () {
$(".slide_btn").on("click", function () {
if (jqXhr) {
// ★通信を中断する★
// ただしfail(), always()は実行される
jqXhr.abort();
return;
}
if (!allowAjax) {
// ★二度押し防止★
return;
}
$('#slideButton').prop('disabled', true);
allowAjax = false;
$(this).toggleClass("active");
$(".slide_box").slideToggle("slow");
DemoAjaxModel.isClose = !DemoAjaxModel.isClose;
jqXhr = $.ajax({
type: 'POST',
url: '/DemoAjax/ConnectByAjax', // アクセス先のURL
data: DemoAjaxModel,
})
.done(function (returnData) {
document.getElementById("result").innerText =
"Success? : " + returnData.isSuccess
+ " Result : " + returnData.result;
jqXhr = null;
allowAjax = true;
$('#slideButton').prop('disabled', false);
});
})
});
</script>
<style type="text/css">
.toggle_box{
display:none;
color:#fff;
background-color:#f26c4f;
padding:20px;
margin-top:20px;
}
.btn{
background-color:#dddddd;
padding:10px;
}
.btn.active{
background-color:#1b325f;
padding:10px;
color:#fff;
}
.btn:hover{
cursor:pointer;
}
.box{
background-color:#132343;
width:100%;
height:20px;
margin-top:20px;
margin-bottom:20px;
}
</style>
</head>
<body>
@Code
ViewData("Title") = "IndexView"
End Code
<h2>Ajax Demo In ASP.NET MVC</h2>
<div id="slideButton" class="slide_btn btn">Click Me!</div>
<div class="slide_box toggle_box">
<p id="result">Result : </p>
</div>
</body>
</html>