【ASP.NET MVC】【VB】【Ajax】ASP.NET MVCのAjax通信時にValidateAntiForgeryToken を使用する

ASP.NET MVCAjax通信時にValidateAntiForgeryToken を使用する

 * Ajax.BeginForm()を使用する
 * 設定については、以下の関連記事を参照のこと。
http://blogs.yahoo.co.jp/dk521123/35611906.html

サンプル

コントローラ

SampleAjaxController.vb
Imports System.Web.Mvc

Namespace Controllers
    Public Class SampleAjaxController
        Inherits Controller

        ' GET: SampleAjax
        Function Index() As ActionResult
            Return View()
        End Function

        ' ★ここ★
        <ValidateAntiForgeryToken()>
        Public Function SayHello(name As String) As ActionResult
            ' リクエストがAjax通信(非同期通信)である場合値を返す
            If Request.IsAjaxRequest() Then

                Return Json(New With {Key .ResultMessage = "Hello, " & name & "!"},
                        JsonRequestBehavior.AllowGet)
            Else
                ' リクエストがAjax通信以外の場合、何もしない
                Return New EmptyResult()

            End If
        End Function

    End Class
End Namespace

ビュー

Index.vbhtml
@Code
    ViewData("Title") = "Index"
End Code
<script src="~/Scripts/jquery-1.10.2.js" type="text/javascript"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.js" type="text/javascript"></script>
<script src="~/Scripts/MicrosoftAjax.js" type="text/javascript"></script>
<script src="~/Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
<-- ★ここ★ -->
@Using Ajax.BeginForm("SayHello",
                New AjaxOptions With {
                .HttpMethod = "POST",
                .UpdateTargetId = "result",
                .OnSuccess = "onSuccess",
                .OnFailure = "onFail"})
    @Html.TextBox("Name", "")
    @Html.AntiForgeryToken()
    @<input type="submit" value="Say Hello" />
End Using

<div id="result"></div>

<script type="text/javascript">
    function onSuccess(data) {
        $('#result').html(data.ResultMessage);
    }
    function onFail() {
        $('#result').html("Fail...");
    }
</script>

関連記事

Html.AntiForgeryToken() / ValidateAntiForgeryToken

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

ASP.NET MVC において、 Ajax でやり取りする [2]

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

ASP.NET MVCでknockout.js を使った際に ValidateAntiForgeryToken を使用する [1] ~試作版~

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

ASP.NET MVCでknockout.js を使った際に ValidateAntiForgeryToken を使用する [2] ~決定版~

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